关闭txt文件并删除它

Close the txt file and delete it

这个函数的最后两行代码有问题,因为文件 file.txt 仍然打开并且没有被删除,并且 tmpFile.txt 没有更改名称。 从 file.txt 复制到 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());*/
}

无法重现。我 运行 你的代码,它替换了文件。

但是,请尝试升级代码以使用更新的 NIO.2 方法:

public static void transfer(Client client) throws IOException {
    Path file = Paths.get("file.txt");
    Path tmpFile = Paths.get("tmpFile.txt");

    try (BufferedReader reader = Files.newBufferedReader(file);
         BufferedWriter writer = Files.newBufferedWriter(tmpFile)) {

        String lineToRemove = client.id + ";" + client.pin + ";" + 
                client.money + ";" + client.name + ";";
        for (String currentLine; (currentLine = reader.readLine()) != null; ) {
            if (! currentLine.trim().equals(lineToRemove))
                writer.write(currentLine + "\n");
        }
    }

    Files.move(tmpFile, file, StandardCopyOption.REPLACE_EXISTING);
}