2009-02-21 62 views
2
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()之後,它仍然存在。 如何確保臨時文件已被刪除。Java RandomAccessFile

在此先感謝。

+0

奇怪...你想要什麼文件? – OscarRyz 2009-02-21 02:31:27

回答

1

改爲使用File.createTempFile()

我意識到,不會給你與RandomAccessFile相同的功能,但你可以建立你所需要的。

其實我甚至不確定你爲什麼要將這些東西寫入文件。這是一種使用跟蹤的東西嗎?爲什麼不把它存儲在內存中?

+0

這是一個struts web應用程序,爲了讓struts下載文件,您需要從文件中流式傳輸。我一直認爲隨機訪問文件是用於創建文件的內存,而不用創建物理文件。 – samsina 2009-02-23 21:25:34

2

我打算假設你只顯示了一小部分代碼,並且有一個很好的理由,那就是你在使用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()方法來包裝它。理論上拋出IOException似乎是檢查異常的濫用,因爲沒有任何事情可以讓調用者做出響應。

5

一個更好的問題是,爲什麼你會想要經歷所有制作文件,寫入文件的事情,然後刪除文件?

無論您不需要隨機訪問文件 - FileWriter會更好。

要確保文件被刪除做埃迪表明,放在一個finnaly塊刪除 - 但你還需要確保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存在時刪除這些文件。

+0

他他嘿嘿...大多數時候,你什麼也沒有做。 ... – OscarRyz 2009-02-21 02:30:23

0

你試過這個嗎?

File temp = File.createTempFile("file", ".tmp"); 
temp.deleteOnExit();