2015-04-07 24 views
1

這是我的方法寫一個文件,這種方法屬於一類的PrintWriter在Java中沒有追加,使用FileOutputStream中

public void write(FileOutputStream fo) throws IOException 
    { 
     PrintWriter out=new PrintWriter(fo); 
     for (int i = 0; i < size; i++) { 
      String formatted="%3d"; 
      for (int j=0;j<size;j++) 
      { 
       out.append(String.format(formatted,arr[i][j])); 
      } 
      out.append(System.getProperty("line.separator")); 
     } 
     out.append(System.getProperty("line.separator")); 
     out.close(); 
    } 

我想寫我的結果到許多不同的文件,相當於輸入文件中讀取通過適當創建的對象,所以我待寫文件作爲參數傳遞給該方法

它不會在所有

追加花了幾個小時尋找這一問題的解決方案後,我只得到了結果使用指定的PrintWriter追加文件的路徑,例如:

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

如果我使用

PrintWriter out=new PrintWriter(new FileWriter(fo,true)); 

我遇到錯誤

它不追加,當我2個該對象的實例的寫入方法被調用

public void writeSolution() throws IOException 
    { 
     fo=new FileOutputStream("output\\output1.txt",true); 
     start.write(fo); 
     goal.write(fo); 
     fo.close(); 
    } 

請幫我解決這個問題

回答

0

當您關閉PrintWriter時,close()方法也會關閉底層的流/寫入器

在每次撥打write方法時,打開PrintWriter,然後在最後關閉它。這意味着流被關閉。下一次你打開一個PrintWriter它,它是一個封閉的文件。您無法寫入已關閉的文件。

A PrintWriter當你做這樣的事情時不會拋出異常,所以它默默無聞。而且你沒有調用checkError()方法,所以你不知道那裏有錯誤。

你應該做的是聲明PrintWriter作爲一個字段(以便保持其調用之間狀態write(),打開它,你開始調用write()方法之前,並關閉它在完成要求的最後write()方法後,時間,並記得檢查錯誤

+0

但是我怎樣才能把fo作爲參數? – necroface

+0

我照你說的做了,它什麼也沒寫到我的文件 – necroface

+0

我設法解決這個問題,謝謝:) – necroface