2016-04-24 121 views
0

我有一個隨機訪問文件,它包含運行時生成的一些信息,當程序終止時需要從目錄中刪除這些信息。從我發現,隨機訪問文件沒有像我發現的常規文件和全部刪除的方法是:從目錄中刪除RandomAccessFile

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

這顯然是行不通的,而我一直沒能找到NetSimView上的任何內容。有任何想法嗎?

回答

0

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()在程序終止時刪除該文件。

+0

謝謝,我注意到用我的RandomAccessFile對象刪除文件,我不認爲只是創建一個常規文件對象來刪除。 – WickedChester