关闭txt文件并将其删除

时间:2019-06-07 17:15:05

标签: java bufferedreader

此函数的后两行代码有问题,因为文件file.txt仍处于打开状态并且未被删除,并且tmpFile.txt不会更改名称。 从file.txttmpFile.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());*/
    }

2 个答案:

答案 0 :(得分:1)

如果我运行的代码中没有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());*/
}

答案 1 :(得分:0)

无法复制。我运行了您的代码,它替换了文件。

但是,请尝试升级代码以使用较新的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);
}