首页 > 解决方案 > 实时写入并删除文件 JAVA 中的最后一个字符

问题描述

我在 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),如果程序以异常方式停止,之前的所有字符串都保存了吗?

非常感谢。

标签: javajsonfilefilewriter

解决方案


我看到了两种可能的方法,这两种方法都是首先不打印它的解决方案。

第一:boolean在while循环中使用a和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("]");

推荐阅读