从目录中删除RandomAccessFile

时间:2016-04-24 22:04:48

标签: java

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

RandomAccessFile temp = new RandomAccessFile ("temp.tmp", "rw");
temp = new File(NetSimView.filename);
temp.delete();

这显然不起作用,我还没能在NetSimView上找到任何东西。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

RandomAccessFile没有删除方法。 为要删除的文件创建新的File对象很好。但是,在执行此操作之前,您需要通过调用RandomAccessFile确保引用同一文件的RandomAccessFile.close()已关闭

如果要在程序终止时删除文件,可以执行以下操作:

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