【问题标题】:Could not delete file in Java无法在 Java 中删除文件
【发布时间】:2019-04-10 21:53:39
【问题描述】:

由于某种原因无法删除和替换文件。

我只想从文件中删除 1 行。我找到了一种方法,方法是创建一个临时文件,然后从原始文件中逐行写入每一行,除了我要删除的行,然后用临时文件替换原始文件,但是虽然临时文件是创建的,但原始文件不能由于某种原因被删除和替换。我检查了文件没有打开。

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 对象,它会抛出一个 IOException,告诉你为什么它不能被删除。

标签: java delete-file


【解决方案1】:

强烈建议使用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 resourcesAutoClosable.

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-03-31
  • 2014-12-18
  • 1970-01-01
  • 1970-01-01
  • 2018-10-16
  • 1970-01-01
相关资源
最近更新 更多