从目录中删除随机访问文件



我有一个随机访问文件,其中包含运行时生成的一些信息,这些信息需要在程序终止时从目录中删除。据我所知,随机访问文件不像常规文件那样具有删除方法,我发现的只是:

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() 在程序终止时删除文件的最后一行代码。

最新更新