我需要帮助来理解Gson库的Jsonwriter选项。基本上,我可以从该位置读取文件。然后我将数据转换为Java List后修改了数据。我可以将修改后的json发送到ajax响应,一切正常。现在我想将这个修改过的json保存在指定的文件中。有一件事我想确保File被清除并用新的json值更新。
//Read File done
//converted to list
//List modified
//converting to Json
String json = new Gson().toJson(myData);
System.out.println(json);
// Sent to ajax response and worked fine
// Now update file with new json...
//JsonWriter writer = new JsonWriter(new FileWriter(ctx.getRealPath("file.text")));
FileWriter writer = new FileWriter(new File(ctx.getRealPath("file.txt")));
writer.write(json);
writer.flush();
writer.close();
提前谢谢!
替代代码------
FileWriter fw = null;
try {
fw = new FileWriter(new File(ctx.getRealPath("file.txt")));
BufferedWriter bw = new BufferedWriter(fw);
bw.write(json);
bw.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fw != null) {
fw.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}