首页 > 解决方案 > 关闭txt文件并删除

问题描述

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

标签: javabufferedreader

解决方案


如果我在没有这些Client东西的情况下运行您的代码,它会按预期工作。

你仍然看到你的file.txt打开的原因是因为那不是你的初始file.txttmpFile.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());*/
}

推荐阅读