如何在不重叠先前数据的情况下编写JSON文件

时间:2019-10-17 08:17:53

标签: java json

import java.io.FileWriter;
import java.io.IOException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

public class writejson {
    //public static void writejs(String attachmentValue)
    public static void main(String[] args) {
        String attachmentValue= "1234";
        {
            JSONObject obj = new JSONObject();
            obj.put("Attachement Id: ", attachmentValue);
            try (FileWriter file = new FileWriter("C:\\failedtestdata.json"))
            {
                file.write(obj.toJSONString());
                file.flush();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

在JSON文件中,不与现有记录重叠。如何在下一行创建新记录

2 个答案:

答案 0 :(得分:2)

1.Use Append true构造函数-类似于FileWriter(“ C:\ failedtestdata.json”,true) 2.在每次写入中添加\ n,因此默认情况下,追加将在下一行开始

答案 1 :(得分:1)

import java.io.FileWriter;
import java.io.IOException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

public class WriteJson {

    public static void main(String[] args) {
        String attachmentValue= "1234";
        JSONObject obj = new JSONObject();
        obj.put("Attachement Id: ", attachmentValue);
        String loc="C:\\failedtestdata.json";
        try (FileWriter file = new FileWriter(loc,true))
        {
         //File Writer creates a file in write mode at the given location 
         file.write(obj.toJSONString());
         file.write(",");
         file.append("\n");
         file.flush();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}