Java 6 File Deletion

后端 未结 2 542
孤街浪徒
孤街浪徒 2021-01-17 14:30

I am aware that this question is a raging duplicate of this question. However, I have now read that entire page twice, and some sections 3 times, and for th

相关标签:
2条回答
  • 2021-01-17 14:40

    You can only delete the file if there is no file handler left opened. Since you open the file hanlder using FileWriter, you will need to close it before you can delete it. In other word, f.delete must be executed after fw.close

    Try the code below. I made the changes to prevent all possible bug you may found, e.g if fw is null.

    File f = null;
    FileWriter fw = null;
    try {
        f = new File("myFile.txt");
        fw = new FileWriter(f);
        fw.write("This is a sentence that should appear in the file.");
        fw.flush(); // flush is not needed if this is all your code does. you data
                    // is automatically flushed when you close fw
    } catch (Exception exc) {
        System.err.println(exc.getMessage());
    } finally {// finally block is always executed.
        // fw may be null if an exception is raised in the construction 
        if (fw != null) {
            fw.close();
        }
        // checking if f is null is unneccessary. it is never be null.
        if (f.delete()) {
            System.out.println("File was successfully deleted.");
        } else {
            System.err.println("File was not deleted.");
        }
    }
    
    0 讨论(0)
  • 2021-01-17 14:57

    You're trying to delete() a file which is still referenced by an active, open FileWriter.

    Try this:

    f = new File("myFile.txt");
    fw = new FileWriter(f);
    fw.write("This is a sentence that should appear in the file.");
    fw.flush();
    fw.close(); // actually free any underlying file handles.
    if(f.delete())
        System.out.println("File was successfully deleted.");
    else
        System.err.println("File was not deleted.");
    
    0 讨论(0)
提交回复
热议问题