java - 关闭txt文件并删除
问题描述
我在这个函数的最后两行代码有问题,因为文件file.txt
仍然打开,没有被删除,tmpFile.txt
也没有更改名称。file.txt
从to复制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());*/
}
解决方案
如果我在没有这些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());*/
}
推荐阅读
- python - 计算球队得分的中位数?
- haskell - 不使用 zipWith 的斐波那契数
- python - 数据框 - 列不存在创建一个
- python - 如何找到python列表之间匹配值对的数量?
- elasticsearch - 弹性搜索 REST 查询返回超出预期
- r - 带有两个变量的点图
- java - GraphQL 查询解析器作为单独的 Web 事务
- python - 首次尝试使用导入请求时 Python 连接被拒绝
- google-bigquery - 如何在不使用 case 语句的情况下在 BigQuery 中创建数据透视表
- plc - 为什么我不能将输出变量作为参数传递给 IEC61131-3 结构化文本 (TwinCAT3) 中的功能块构造函数?