[英]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.