无法删除文件Java [英] Cannot delete file Java

查看:322
本文介绍了无法删除文件Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这种方法来获取.txt文件的最后一行,并创建一个没有该行的新临时文件。但是,当我尝试删除包含要删除的行的.txt文件时(出于某种原因,我可以重命名临时文件),我无法这样做。这是代码:

I have this method that gets the last line of a .txt file and creates a new temp file without that line. But when I try to delete the .txt that has the line I want to delete (so then I can rename the temp file) for some reason I can't. This is the code:

void removeFromLocal() throws IOException {
    String lineToRemove = getLastLine();
    File inputFile = new File("nexLog.txt");
    File tempFile = new File("TempnexLog.txt");
    BufferedReader reader = null;
    BufferedWriter writer = null;
    try {

        reader = new BufferedReader(new FileReader(inputFile));
        writer = new BufferedWriter(new FileWriter(tempFile));

        String currentLine;
        int i = 0;
        while ((currentLine = reader.readLine()) != null) {
            i++;                
            String trimmedLine = currentLine.trim();
            if (!trimmedLine.equals(lineToRemove)) {
                if (i != 1) {
                    writer.newLine();
                }
                writer.write(currentLine);
            }
        }
            reader.close();
            reader = null;
            writer.flush();
            writer.close();
            writer = null;
            System.gc();

            inputFile.setWritable(true);

            if (!inputFile.delete()) {
                System.out.println("Could not delete file");
                return;
            }


            if (!tempFile.renameTo(inputFile)) {
                System.out.println("Could not rename file");
            }
        //boolean successful = tempFile.renameTo(inputFile);
    } catch (IOException ex) {
        Logger.getLogger(dropLog.class.getName()).log(Level.SEVERE, null, ex);
    }
}

有趣的是,当我按下呼叫按钮时方法一次,什么也没发生(无法删除文件),第二次工作正常,第三次我得到无法重命名文件。

Whats funny is that when I press the button that calls the method once, nothing happens ("Could not delete file"), the second time it works fine and the 3rd I get "Could not rename file".

推荐答案

BufferedReader 是否关闭嵌套的阅读器(文档中未提及)?您必须通过检查 setWritable 是否成功来确保,否则也需要关闭 FileReader ,我会推荐使用,因为万一您将其关闭两次不会有任何危害...顺便说一下,GC调用有害无益。

Does BufferedReader close the nested reader (not mentioned in the doc)? You have to make sure, by checking if setWritable was successful.Otherwise you need to close FileReader too, and I would recommend because in case you close it twice there is no harm... by the way GC call is more harmful than useful.

这篇关于无法删除文件Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆