Cannot delete file Java

2019-09-06 14:33发布

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".

2条回答
仙女界的扛把子
2楼-- · 2019-09-06 15:09

The file cannot be deleted when it's been opened by another process. E.g. in notepad or so or maybe even another FileReader/FileWriter on the file somewhere else in your code. Also, when you're executing this inside an IDE, you'll risk that the IDE will touch the file during the background scan for modifications in the project's folder. Rather store the files in an absolute path outside the IDE's project.

Also, the code flow of opening and closing the files has to be modified so that the close is performed in the finally block. The idiom is like this:

Reader reader = null;

try {
    reader = new SomeReader(file);
    // ...
} finally {
    if (reader != null) try { reader.close(); } catch (IOException logOrIgnore) {}
}

Or, if you're already on Java 7, use the automatic resource management instead.

try (Reader reader = new SomeReader(file)) {
    // ...
}

Further I recommend to use File#createTempFile() instead to create temp files. This way an unique temp filename will be generated and thus you prevent the very same temp file being written and renamed by multiple processes.

File tempFile = File.createTempFile("nexLog", ".txt");
查看更多
老娘就宠你
3楼-- · 2019-09-06 15:25

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.

查看更多
登录 后发表回答