我有一个随机访问文件,其中保存了运行时生成的一些信息,当程序终止时需要从目录中删除这些信息。据我发现,随机访问文件没有像常规文件那样的删除方法,我发现的是:
RandomAccessFile temp = new RandomAccessFile ("temp.tmp", "rw");
temp = new File(NetSimView.filename);
temp.delete();
这显然不起作用,而且我在 NetSimView 上找不到任何东西。有什么想法吗?
最佳答案
RandomAccessFile
没有删除方法。
为要删除的文件创建一个新的 File
对象就可以了。但是,在此之前,您需要确保通过调用 RandomAccessFile.close()
RandomAccessFile
如果您想在程序终止时删除该文件,您可以执行以下操作:
File file = new File("somefile.txt");
//Use the try-with-resources to create the RandomAccessFile
//Which takes care of closing the file once leaving the try block
try(RandomAccessFile randomFile = new RandomAccessFile(file, "rw")){
//do some writing to the file...
}
catch(Exception ex){
ex.printStackTrace();
}
file.deleteOnExit(); //Will delete the file just before the program exits
请注意 try
语句上方的注释,使用 try-with-resources,还要注意我们调用 file.deleteOnExit()
进行删除的最后一行代码程序终止时的文件。
关于java - 从目录中删除 RandomAccessFile,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36829417/