java - Java - 读取文件后删除文件
问题描述
我试图弄清楚为什么我的 inputFile.delete() 不会删除该文件。在查看了许多主题之后,看起来有些东西仍在使用该文件,因此不会删除。但我无法弄清楚。我错过了什么??
File inputFile = new File("data/Accounts.txt");
File tempFile = new File("data/tmp.txt");
try {
tempFile.createNewFile();
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String line;
int i = 0;
for (User u : data) {
String toRemove = getIDByUsername(username);
while ((line = reader.readLine()) != null) {
if (line.contains(toRemove + " ")) {
line = (i + " " + username + " " + getStatusByUsername(username) + " " + password);
}
writer.write(line + "\n");
i++;
}
}
reader.close();
writer.close();
} catch (FileNotFoundException e) {
ex.FileNotFound();
} catch (IOException ee) {
ex.IOException();
} finally {
inputFile.delete();
tempFile.renameTo(inputFile);
}
解决方案
通过使用,您可以更短更轻松java.nio
:
public static void main(String[] args) {
// provide the path to your file, (might have to be an absolute path!)
Path filePath = Paths.get("data/Accounts.txt");
// lines go here, initialize it as empty list
List<String> lines = new ArrayList<>();
try {
// read all lines (alternatively, you can stream them by Files.lines(...)
lines = Files.readAllLines(filePath);
// do your logic here, this is just a very simple output of the content
System.out.println(String.join(" ", lines));
// delete the file
Files.delete(filePath);
} catch (FileNotFoundException fnfe) {
// handle the situation of a non existing file (wrong path or similar)
System.err.println("The file at " + filePath.toAbsolutePath().toString()
+ " could not be found." + System.lineSeparator()
+ fnfe.toString());
} catch (FileSystemException fse) {
// handle the situation of an inaccessible file
System.err.println("The file at " + filePath.toAbsolutePath().toString()
+ " could not be accessed:" + System.lineSeparator()
+ fse.toString());
} catch (IOException ioe) {
// catch unexpected IOExceptions that might be thrown
System.err.println("An unexpected IOException was thrown:" + System.lineSeparator()
+ ioe.toString());
}
}
这将打印文件的内容,然后将其删除。
您将想做一些不同的事情,而不仅仅是打印内容,但这也是可能的 ;-) 尝试一下...
推荐阅读
- svg - 如何通过访问 css 样式在 html 中引用 SVG
- azure-devops - 一些 Azure DevOps 现有组织管道存在问题
- angular - ng packager - Angular 10 中未生成 .metadata.json 文件
- charts - PhpSpreadSheet 图表 TYPE_BARCHART_3D 自定义颜色
- git - VSTS:如何在从该分支合并(执行拉取请求)之前要求一个分支是最新的?
- python - 在 Python 中解析自定义逻辑语句
- python - Pytest:使用假设生成总和为 1 的浮点数列表
- apache-kafka - 批量创建Kafka Connector
- laravel - 使用 Laravel MIX 将多个 CSS 编译为一个 CSS
- json - Flutter:当我尝试在 post requestFl 的正文中将 int 转换为 json 时出错