2013-12-14 164 views
1

我寫一個文本文件的代碼現在看起來是這樣的:附加文件,而不是覆蓋它?

public void resultsToFile(String name){ 
    try{ 
    File file = new File(name + ".txt"); 
    if(!file.exists()){ 
     file.createNewFile(); 
    } 
    FileWriter fw = new FileWriter(file.getAbsoluteFile()); 
    BufferedWriter bw = new BufferedWriter(fw); 
    bw.write("Titel: " + name + "\n\n"); 
    for(int i = 0; i < nProcess; i++){ 
     bw.write("Proces " + (i) + ":\n"); 
     bw.write("cycles needed for completion\t: \t" + proc_cycle_instr[i][0] + "\n"); 
     bw.write("instructions completed\t\t: \t" + proc_cycle_instr[i][1] + "\n"); 
     bw.write("CPI: \t" + (proc_cycle_instr[i][0]/proc_cycle_instr[i][1]) + "\n"); 
    } 
    bw.write("\n\ntotal Cycles: "+totalCycles); 
    bw.close(); 
    }catch(IOException e){ 
     e.printStackTrace(); 
    } 
} 

然而,這將覆蓋我以前的文本文件,而不是我希望它被添加到已存在的文件!我究竟做錯了什麼?

+1

[麻煩與FileWriter的覆蓋文件而不是追加到端(的可能重複http://stackoverflow.com/問題/ 10804286 /故障與-的FileWriter-覆蓋 - 文件 - INSTEAD-OF-追加到的終端) – Raedwald

回答

4
FileWriter fw = new FileWriter(file.getAbsoluteFile() ,true); 

開放的javadoc的追加模式。

public FileWriter(File file, boolean append) throws IOException 

Constructs a FileWriter對象給定的File對象。如果第二個參數爲true,則字節將寫入文件的末尾而不是開頭。

1

使用

FileWriter fw = new FileWriter(file.getAbsoluteFile(), true); 

追加到該文件,並採取通過傳遞附加真正看FileWriter(String, boolean)

0
public FileWriter(File file, boolean append) throws IOException { 
} 

使用這種方法:

的JavaDoc:

/** 
    * Constructs a FileWriter object given a File object. If the second 
    * argument is <code>true</code>, then bytes will be written to the end 
    * of the file rather than the beginning. 
    * 
    * @param file a File object to write to 
    * @param  append if <code>true</code>, then bytes will be written 
    *      to the end of the file rather than the beginning 
    * @throws IOException if the file exists but is a directory rather than 
    *     a regular file, does not exist but cannot be created, 
    *     or cannot be opened for any other reason 
    * @since 1.4 
    */ 
相關問題