【发布时间】:2020-08-19 20:29:06
【问题描述】:
我正在转换 json 中的 txt,并且我正在使用 json-simple。 我希望文件是实时写入的,也就是每一行,为此我选择不使用JsonArray, 因为如果我使用 JSONArray,我必须先等待它完成,然后再将其写入文件。 所以我只使用 JsonObjects。 我必须创建一个“隐藏”JsonArray 的问题,为此我在文件的开头和结尾添加方括号,然后在每个 JsonObject 中添加一个逗号。 明显逗号在文件末尾“]”之前打印的问题,如何删除最后一个逗号?
br = new BufferedReader(new FileReader(pathFile + ".txt"));
JSONObject stringDetails = new JSONObject();
JSONArray stringList = new JSONArray();
try (FileWriter file = new FileWriter(pathfile+".json",true)) {
file.write("[");
while ((line = br.readLine()) != null) {
//Miss the code to convert from txt string to json string ...
stringDetails.put(stringJson.getKey(), stringJson.getMessage());
file.write(String.valueOf(stringDetails)+",");
stringDetails = new JSONObject();
}
file.write("]");
}
另外一个问题是,使用append(true),万一程序异常停止,之前的字符串都会被保存?
非常感谢。
【问题讨论】:
标签: java json file filewriter