2011-10-06 26 views
2

我有寫入文件中的以下功能:寫入一個文本文件,在java中

public void writeToFile(String data) throws IOException { 
    FileWriter fstream = null; 


    try { 
     fstream = new FileWriter("out.txt"); 
     BufferedWriter out = new BufferedWriter(fstream); 
     out.write(data); 
     //Close the output stream 
     out.close(); 
    } catch (IOException ex) { 
     Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex); 
    } finally { 
     try { 
      fstream.close(); 
     } catch (IOException ex) { 
      Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex); 
     } 
    } 
} 

它能做什麼每次調用它會創建一個新的文件,並寫入一個新行時間。我想要實現的是檢查文件是否存在。如果不創建一個新文件並寫入一些內容,如果存在,則打開該文件並添加一個新行,而不刪除現有文本。怎麼做?

+0

ISFILE(指定:Java文檔中)如果文件存在則返回true,否則返回false。 – Waltzy

+0

或者自己保存一些代碼:'com.google.common.io.Files.append(CharSequence,File,Charset)' – artbristol

回答

6

改變你的FileOutputStream中的構造函數調用此:

fstream = new FileWriter("out.txt", true); 
2

的FileWriter需要在附加額外的參數,如果你想創建一個新的文件或附加到現有的文件

fstream = new FileWriter("out.txt", true); 

http://download.oracle.com/javase/7/docs/api/java/io/FileWriter.html#FileWriter(java.io.File,%20boolean

+1

+1,無法理解爲什麼其他答案有更多的投票,這是一個更好的答案,儘管鏈接可能會更好,因爲http://download.oracle.com/javase/6/docs/api/java/io/FileWriter.html#FileWriter(java.lang.String,%20boolean) – Qwerky