【问题标题】:Write in Real Time and Remove last character in file JAVA实时写入并删除文件 JAVA 中的最后一个字符
【发布时间】: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


    【解决方案1】:

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

    首先:在 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("]");
    

    【讨论】:

    猜你喜欢
    • 2013-09-22
    • 2020-12-30
    • 2021-11-06
    • 2012-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-01
    相关资源
    最近更新 更多