我有一個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
的每一次迭代,文件不斷被覆蓋。
上面的代碼不會像你所描述的那樣執行。要麼你只有一次迭代,要麼你做了與你期望的不同的事情。我建議你在調試器中逐步瀏覽代碼,看看它在做什麼。 –
@PeterLawrey在最後一段OP中,他補充說,整個代碼在for循環中,並使用分隔符來知道該文件中的每個單獨的json對象。我誤解了嗎? –