简体   繁体   English

从目录中删除RandomAccessFile

[英]Delete RandomAccessFile from directory

I have a random access file that holds some information generated at run time that needs to be deleted from the directory when the program terminates. 我有一个随机访问文件,其中包含运行时生成的一些信息,需要在程序终止时从目录中删除。 From what I have found, random access files don't have a delete method like regular files and all that I have found is: 根据我的发现,随机访问文件没有像常规文件这样的删除方法,我发现的所有内容都是:

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

This obviously doesn't work, and I haven't been able to find anything on NetSimView. 这显然不起作用,我无法在NetSimView上找到任何东西。 Any ideas? 有任何想法吗?

RandomAccessFile does not have a delete method. RandomAccessFile没有删除方法。 Creating a new File object for the file to be deleted is fine. 为要删除的文件创建新的File对象很好。 However, before doing that, you need to insure the RandomAccessFile that references the same file is closed by calling RandomAccessFile.close() 但是,在执行此操作之前,您需要通过调用RandomAccessFile.close()来确保引用同一文件的RandomAccessFile已关闭。

If you want to have the file deleted when the program terminates, you can do something like: 如果要在程序终止时删除文件,可以执行以下操作:

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

Notice the comments above the try statement, using a try-with-resources and also notice the last line of code where we call file.deleteOnExit() to delete the file upon program termination. 注意try语句上面的注释,使用try-with-resources并注意最后一行代码,我们调用file.deleteOnExit()来在程序终止时删除文件。

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

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