我试图弄清为什么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);
}
答案 0 :(得分:3)
使用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());
}
}
这将打印文件的内容,然后将其删除。
您将希望做一些不同的事情,而不仅仅是打印内容,但这也是可能的;-)尝试一下...
答案 1 :(得分:0)
我试图弄清楚为什么inputFile.delete()无法删除文件。
这是因为旧文件API特别以这种方式糟糕透顶:它无法告诉您某些失败的原因。它所能做的就是返回'false'。
请参阅@deHaar的另一个答案,其中显示了如何使用较新的API来执行此操作。除了提供更简洁的代码和更新的API给您更多选择之外,更新的API还解决了此问题,其中各种方法(例如File.delete()
不能告诉您无法执行您的要求的原因。
您的代码有很多很多问题,这就是为什么我强烈建议您进行deHaar尝试的原因。发挥作用:
FileReader
和FileWriter
的构造函数。幸运的是,如果您未能指定编码方式,那么新API的默认默认设置为UTF_8。username
变量在您遍历时似乎没有更新。如果确实没有更新,则将该行移出循环。