我正在使用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),如果程序以异常方式停止,则保存之前的所有字符串吗?
非常感谢。
我看到了两种可能的方式,并且两者都是解决不首先打印它的解决方案。
首先:在while循环中使用boolean
和if语句在条目之前打印逗号(第一个除外)
boolean isFirst = 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());
if (isFirst) {
isFirst = false;
} else {
// print the comma before the new entry
file.write(",");
}
file.write(String.valueOf(stringDetails));
stringDetails = new JSONObject();
}
file.write("]");
第二:第二种方法是拥有私有帮助器方法来将条目打印到文件中,例如:
private static void printEntry(FileWriter file, String line, ... /* what ever else you need*/) {
//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();
}
并使用它来提取while循环中第一个条目的文字,例如:
file.write("[");
if ((line = br.readLine()) != null) {
// print first entry
printEntry(file, line, ...);
// print the rest
while ((line = br.readLine()) != null) {
file.write(",");
printEntry(file, line, ...);
}
}
file.write("]");