2014-01-08 77 views
0

我有一個arraylist(result_arraylist),並使用gson庫將java對象轉換爲JSON,然後將其打印到文本文件中。這裏是我的代碼:爲什麼我的文件不斷被覆蓋?

Gson gson = new Gson(); 
File file = new File(file_path); 
FileWriter fWriter; 
BufferedWriter bWriter; 

try { 
    //create the file if it doesn't exist 
    if((!file.exists())) { 
     file.createNewFile(); 
    } 
    fWriter = new FileWriter(file.getAbsoluteFile()); 
    bWriter = new BufferedWriter(fWriter); 
    for(int j = 0; j < result_arraylist.size(); ++j) { 
     bWriter.write("<!--"); //this and the last string I write to the file is just to separate the objects for when I read the file again 
      bWriter.newLine(); 
     bWriter.write(gson.toJson(result_arraylist.get(j))); //take the object at index j, convert it to JSON and write to file 
      bWriter.newLine(); 
     bWriter.write("-->"); //seperator to denote end of object 
      bWriter.newLine(); 
      bWriter.newLine(); 
    } 
} 
catch(IOException e) {e.printStackTrace();} 

什麼我沒在這裏展示的是,這是嵌套在與每個迭代不同的對象罷了result_arraylist較大for loop。我的問題是,主for loop的每一次迭代,文件不斷被覆蓋。

+0

上面的代碼不會像你所描述的那樣執行。要麼你只有一次迭代,要麼你做了與你期望的不同的事情。我建議你在調試器中逐步瀏覽代碼,看看它在做什麼。 –

+0

@PeterLawrey在最後一段OP中,他補充說,整個代碼在for循環中,並使用分隔符來知道該文件中的每個單獨的json對象。我誤解了嗎? –

回答

3

以附加模式打開File,傳遞true至FileWriter(String fileName, boolean append)構造函數,以便它不會覆蓋現有內容。

構造一個FileWriter對象,給定一個帶有指示是否附加寫入數據的布爾值的文件名。

fWriter = new FileWriter(file.getAbsoluteFile(), true); 
+1

幾個星期前有這個問題,這正是我所做的修復它。 +1 –

+0

謝謝蘇雷什。這對我有效。 – user3015565

+0

@ user3015565所以這意味着你一次只能寫一個,你需要附加一個而不是破壞以前的數據。 –

0

因爲這是在環路較大,每次運行這段代碼,你再次打開該文件。重新打開文件默認爲覆蓋它。

在外部循環之外打開文件可能會更好,您將避免此問題。

如果您確實想要像您一樣多次打開文件,請使用append標誌,如Suresh所述。

相關問題