此函数的后两行代码有问题,因为文件file.txt
仍处于打开状态并且未被删除,并且tmpFile.txt
不会更改名称。
从file.txt
到tmpFile.txt
的复制效果很好。
我正在寻求帮助
public static void transfer(Client client) throws FileNotFoundException, IOException{
File file = new File("file.txt");
File tmpFile = new File("tmpFile.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
BufferedWriter writer = new BufferedWriter(new FileWriter(tmpFile));
try{
String lineToRemove = client.id + ";" + client.pin + ";" +
client.money + ";" + client.name + ";";
String currentLine;
while((currentLine = reader.readLine()) != null) {
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(lineToRemove)) continue;
writer.write(currentLine + "\n");
}
}
finally{
writer.close();
reader.close();
}
file.delete();
tmpFile.renameTo(file);
/*File oldFile = new File("tmpFile.txt");
File newFile = new File(oldFile.getParent(), "file.txt");
Files.move(oldFile.toPath(), newFile.toPath());*/
}
答案 0 :(得分:1)
如果我运行的代码中没有Client
东西,那么它将按预期工作。
您仍然看到file.txt
打开的原因是因为那不是您的初始file.txt
。它是重命名的tmpFile.txt
,现在称为file.txt
。
在下面的代码中,您剩下的文件已从tmpFile.txt
重命名为file.txt
,其中包含“ HALLO \ n”。实际上,初始文件file.txt
已被删除,并且不再存在。 -那就是预期的行为。
public static void main(String[] args) throws Exception {
File file = new File("src/file.txt");
File tmpFile = new File("src/tmpFile.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
BufferedWriter writer = new BufferedWriter(new FileWriter(tmpFile));
try{
writer.write("HALLO" + "\n");
}
finally {
writer.close();
reader.close();
}
file.delete();
tmpFile.renameTo(file);
/*File oldFile = new File("tmpFile.txt");
File newFile = new File(oldFile.getParent(), "file.txt");
Files.move(oldFile.toPath(), newFile.toPath());*/
}
答案 1 :(得分:0)
无法复制。我运行了您的代码,它替换了文件。
但是,请尝试升级代码以使用较新的NIO.2方法:
public static void transfer(Client client) throws IOException {
Path file = Paths.get("file.txt");
Path tmpFile = Paths.get("tmpFile.txt");
try (BufferedReader reader = Files.newBufferedReader(file);
BufferedWriter writer = Files.newBufferedWriter(tmpFile)) {
String lineToRemove = client.id + ";" + client.pin + ";" +
client.money + ";" + client.name + ";";
for (String currentLine; (currentLine = reader.readLine()) != null; ) {
if (! currentLine.trim().equals(lineToRemove))
writer.write(currentLine + "\n");
}
}
Files.move(tmpFile, file, StandardCopyOption.REPLACE_EXISTING);
}