您好,我的代码基本上是从txt文件中删除空行,但是我想在临时文件的末尾使用原始名称。
String inputFileName = "src/inware/users.txt";
String outputFileName = "src/inware/usersT.txt";
try (BufferedReader inputFile = new BufferedReader(new FileReader(inputFileName));
PrintWriter outputFile = new PrintWriter(new FileWriter(outputFileName))) {
String lineOfText;
while ((lineOfText = inputFile.readLine()) != null) {
lineOfText = lineOfText.trim();
if (!lineOfText.isEmpty()) {
outputFile.println(lineOfText);
}
}
inputFile.close();
outputFile.close();
inputFile.delete();
outputFile.renameTo(inputFile);
} catch (IOException ex) {
Logger.getLogger(ManageStudentController.class.getName()).log(Level.SEVERE, null, ex);
}
我尝试
inputFile.delete();
outputFile.renameTo(inputFile);
但是不起作用...任何解决方案?
答案 0 :(得分:1)
使用新的File NIO.2 API代替旧的过时的File I / O API。
这意味着您应该改用Files.delete(Path path)
和Files.move(Path source, Path target)
,因为如果操作失败,它们会抛出异常,说明为什么,而不是仅仅返回无意义的{{1 }}值就像旧的File
方法一样。
此外,由于您使用的是 try-with-resources ,因此请不要自己关闭流。要关闭资源时,请关闭false
块。
将代码更改为:
try
import java.io.*;
import java.nio.file.*;
import java.util.logging.*;
如果delete + rename失败,您现在将知道原因。
答案 1 :(得分:0)
我找到了解决问题的更好的解决方案:
Path p = Paths.get("src", "inware", "users.txt");
try {
Path tempFile = Files.createTempFile(p.getParent(), "usersTemp", ".txt");
try (BufferedReader in = Files.newBufferedReader(p);
PrintWriter out = new PrintWriter(Files.newBufferedWriter(tempFile))) {
for (String line; (line = in.readLine()) != null;) {
line = line.trim();
if (!line.isEmpty()) {
out.println(line);
}
}
}
Files.copy(tempFile, p, StandardCopyOption.REPLACE_EXISTING);
Files.delete(tempFile);
} catch (IOException ex) {
Logger.getLogger(ManageStudentController.class.getName()).log(Level.SEVERE, null, ex);
}