[英]Java RandomAccessFile
public void exportUrlsToFile(String file, String urls) throws IOException {
String[] urlsArray = urls.split("\\s+");// split on one or more white space characters.
// create a fresh file
RandomAccessFile raf = new RandomAccessFile(file, "rw");
for (String line : urlsArray) {
line = line.trim();
if (line.isEmpty()) {// this won't happen!
continue;
}
raf.writeBytes(line);
raf.writeBytes(newline);
}
// close the file handler
raf.close();
}
基本上,我使用這個類來做一些事情。 這是在 Tomcat JVM 中運行的應用程序的一部分。 我注意到,無論何時調用此方法,它都會創建一個與參數同名的文件,並且在 raf.close() 之后,它仍然存在。 如何確保刪除臨時文件?
一個更好的問題是為什么你要經歷制作文件的所有麻煩,向文件寫入內容,然后刪除文件?!
不管你不需要隨機訪問文件 - FileWriter 會更好。
為了確保文件被刪除,按照 Eddie 的建議執行並將刪除放在最后一個塊中 - 但您還需要確保 raf.close() IOException 被處理......類似於:
} finally { try { raf.close(); } catch(final IOException ex) { // in 14 years of Java programming I still don't know what to do here! ;-) } finally { File todelete = new File(file); if (!todelete.delete()) { // Log a complaint that we couldn't delete the temp file } } }
編輯:
您可能還表示,在 Tomcat 進程完成后,文件仍然存在並且您希望它消失。 如果是這種情況,請查看 java.io.File.deleteOnExit()。 當Tomcat JVM存在時,這應該刪除文件。
我將假設您只展示了代碼的一小部分,並且當似乎沒有進行任何隨機訪問時,您使用RandomAccessFile
是有充分理由的。
我會做這樣的事情:
public void exportUrlsToFile(String file, String urls) throws IOException {
String[] urlsArray = urls.split("\\s+");
// create a fresh file
RandomAccessFile raf = new RandomAccessFile(file, "rw");
try {
for (String line : urlsArray) {
line = line.trim();
if (line.isEmpty()) { // this won't happen!
continue;
}
raf.writeBytes(line);
raf.writeBytes(newline);
}
} finally {
// don't leak file handles on Exception -- put close in "try/finally"
try { raf.close(); } catch (IOException e) { /* ignore */ }
File todelete = new File(file);
if (!todelete.delete()) {
// Log a complaint that we couldn't delete the temp file
}
}
}
編輯:我同意,我們不希望 close() 上的理論 IOException 引起問題。 比忽略它更好的是記錄“我們從沒想過會看到這個......”,但有例外。 我經常創建一個 closeWithoutException() 方法來包裝它。 Close 理論上拋出 IOException 似乎是對檢查異常的濫用,因為您無法期望調用者做出任何響應。
我意識到這不會為您提供與 RandomAccessFile 相同的功能,但您可以在此基礎上構建您需要的功能。
實際上,我什至不確定您為什么要將這些東西寫入文件。 這是某種使用情況跟蹤嗎? 為什么不把它存儲在內存中?
你試過這個嗎?
File temp = File.createTempFile("file", ".tmp");
temp.deleteOnExit( );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.