繁体   English   中英

从目录中删除RandomAccessFile

[英]Delete RandomAccessFile from directory

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

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()来在程序终止时删除文件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM