Java 6 文件删除
Java 6 文件删除
我知道这个问题是一个激烈的重复问题,参考链接如下:此题。但是,我已经两次阅读了整个页面,并有些部分读了三遍,但我实在看不出来它是在哪里/如何回答这个问题!
所以,接下来是我的问题。
我现在正在工作,不得不使用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(); }
它没有抛出任何可抛出的、错误或异常(我包含了这些以排除任何和所有边缘情况)。第二个打印语句(\"File was not deleted.\"
)被打印到控制台。我在Windows 7上运行此程序,并写入具有完全权限(rwx)的文件夹中。
我参考的提问者已经自己回答了自己的问题,但以我当时的观点,他/她不是以一个很直接的方式回答的。无论如何,我很难理解它的意思。他/她似乎在暗示用BufferedReader
而不是FileInputStream
,对他/她有所帮助,但我不知道它如何适用。
Java 7似乎通过引入java.nio.file.Files
类来解决了此问题,但是,我不能使用Java 7,原因超出了我能够控制的范围。
那个问题的其他回答者暗示这是Java中的“错误”,并提供各种解决方法,例如显式调用 System.gc()
等。我已经尝试了所有这些方法,但它们都没有起作用。或许有人可以提供新的观点,为我激发一些思考。
如果没有文件句柄打开,您才能删除文件。由于您使用FileWriter
打开文件句柄,因此在删除之前必须关闭它。换句话说,在执行fw.close
之后必须执行f.delete
尝试下面的代码。我对它进行了更改,以防您可能遇到的所有可能出现的错误,例如如果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."); } }
您正在尝试删除一个仍被活动、打开的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.");