由于某种原因,无法删除和替换文件。
我想从文件中只删除1行。我找到了一种方法,通过创建一个临时文件,然后逐个写入原始文件中的每一行,除了我要删除的行,然后用temp替换原始文件,但是虽然临时文件是创建的原始文件不能由于某种原因被删除和替换。我检查过文件没有打开。
File inputFile = new File("epafes.txt");
File tempFile = new File("epafesTemp.txt");
BufferedReader reader2 = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String lineToRemove = del;
String currentLine;
while((currentLine = reader2.readLine()) != null) {
// trim newline when comparing with lineToRemove
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(lineToRemove)) continue;
writer.write(currentLine + System.getProperty("line.separator"));
}
writer.close();
reader2.close();
if (!inputFile.delete()) {
System.out.println("Could not delete file");
return;
}
//Rename the new file to the filename the original file had.
if (!tempFile.renameTo(inputFile))
System.out.println("Could not rename file");
}
强烈建议使用java.nio.file.Files#delete(Path)
方法而不是File#delete
。阅读相关的question。此外,您不必删除文件并写入临时文件。只需阅读文本,根据需要对其进行过滤,最后从头开始重新编写相同的文件。 (当然写作必须先关闭。)
看看这个例子:
public class ReadWrite {
public static void main(String[] args) {
File desktop = new File(System.getProperty("user.home"), "Desktop");
File txtFile = new File(desktop, "hello.txt");
StringBuilder sb = new StringBuilder();
try (BufferedReader br = new BufferedReader(new FileReader(txtFile))) {
String line;
while ((line = br.readLine()) != null) {
if ("this should not be read".equals(line))
continue;
sb.append(line);
sb.append(System.lineSeparator());
}
} catch (IOException e) {
System.err.println("Error reading file.");
e.printStackTrace();
}
try (PrintWriter out = new PrintWriter(txtFile)) {
out.write(sb.toString());
} catch (IOException e) {
System.err.println("Error writing to file.");
e.printStackTrace();
}
}
}
初始hello.txt内容:
hello there
stackoverflow
this should not be read
but what if it does?
then my answer
is going to get downvotes
运行后:
hello there
stackoverflow
but what if it does?
then my answer
is going to get downvotes
P.S:如果您使用Java 8+,请查看try-with resources和AutoClosable.