Java 6文件删除

IAm*_*aja 11 java io file java-6

我知道这个问题的肆虐重复这个问题.但是,我现在已经阅读了整个页面两次,有些部分已经阅读了3次,而对于我的生活,我看不出它是如何/在哪里被回答的!

所以,关于我的问题.

我正在工作,我被困在使用Java 6 SE并且无法升级到7.我正在编写一个程序,它创建一个文件,写入它,进行一些处理,然后需要删除该文件.我遇到了与上面提到的问题的人完全相同的问题:Java不会删除文件,我无法弄清楚原因.

代码:

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();
    if(f.delete())
        System.out.println("File was successfully deleted.");
    else
        System.err.println("File was not deleted.");
}
catch(Exception exc)
{
    System.err.println(exc.getMessage());
}
catch(Error er    {
    System.err.println(er.getMessage());
}
catch(Throwable t)
{
    System.err.println(t.getMessage());
}
finally
{
    fw.close();
}
Run Code Online (Sandbox Code Playgroud)

它不会抛出任何抛出物,错误或异常(我包括那些排除任何和所有边缘情况).第二个print语句("File was not deleted.")正在打印到控制台.我在Windows 7上运行它,并写入我拥有完全权限(rwx)的文件夹.

用户问我引用的问题回答了他自己的问题,但是(以我的拙见)以一种不那么直接的方式这样做了.无论如何,我无法理解它.他/她似乎暗指使用a BufferedReader而不是FileInputStream为他/她做出改变,但我只是不明白这是如何适用的.

Java 7似乎已经通过引入java.nio.file.Files类修复了这个问题,但同样,我不能将Java 7用于我控制范围之外的原因.

对该引用问题的其他回答者提到这是Java中的"bug",并提供各种规避,例如明确调用System.gc()等.我已经尝试了所有这些并且它们无法正常工作.

也许有人可以添加一个新的视角,并为我慢慢思考.

mcf*_*gan 18

您正在尝试删除()仍由活动的,打开的FileWriter引用的文件.

试试这个:

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.");
Run Code Online (Sandbox Code Playgroud)


gig*_*dot 8

如果没有打开文件处理程序,则只能删除该文件.由于您使用打开hanlder文件FileWriter,因此需要先关闭它才能删除它.换句话说,f.delete必须在执行之后执行fw.close

请尝试下面的代码.我进行了更改以防止您可能发现的所有可能的错误,例如,如果fw为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.");
    }
}
Run Code Online (Sandbox Code Playgroud)