Cannot delete file Java

≡放荡痞女 提交于 2019-12-12 02:54:17

问题


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


回答1:


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.




回答2:


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");


来源:https://stackoverflow.com/questions/9502983/cannot-delete-file-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!