![](/img/trans.png)
[英]How would i get my code to join data together instead of overwriting the .txt file with each new stream
[英]How can i add a new object to my json file in java instead of overwriting it?
我目前正在构建一个 GSONFileWriter class。
public class GSONFileWriter {
private File jsonFile;
private final String json;
public GSONFileWriter(String json) {
this.json = json;
}
public void generateJsonFileIfNotExists(String pathname) {
try {
jsonFile = new File(pathname);
if (!jsonFile.exists()) {
if (jsonFile.createNewFile()) {
System.out.println("File successful created.");
} else {
System.out.println("Error: Building the file went wrong!");
System.exit(1);
}
}
fillJsonFile();
} catch (Exception e) {
System.err.println("Error: Building the file went wrong!");
}
}
private void fillJsonFile() {
try (PrintWriter writer = new PrintWriter(jsonFile, StandardCharsets.UTF_8)) {
writer.append(json);
writer.println();
} catch (Exception e) {
e.printStackTrace();
}
}
}
它在我的 CLI class 中被调用
Gson gson = new Gson();
String json = gson.toJson(target);
GSONFileWriter gsonFileWriter = new GSONFileWriter(json);
gsonFileWriter.generateJsonFileIfNotExists("EmployeeData.json");
它创建并构建一个新的 JSON 文件,其中包含一个 object。
{"salary":34000.0,"name":"Hans","age":30,"id":"d40507a7-a802-4494-9a0c-5a97a0a4d0bf"}
但是问题是,每当我再次运行代码时,旧文件都会被覆盖并创建一个新文件。 我试图更改代码,以便它向文件添加一个新的 object,而不是覆盖它。 有小费吗?
我会建议:首先:如果 json 文件存在,请将其读取为字符串。
String file = "<File>";
String json = new String(Files.readAllBytes(Paths.get(file)));
其次,使用 JsonParser 将此字符串转换为 JsonObject:
JsonObject object = JsonParser.parseString(json).getAsJsonObject();
现在您获得了作为 JsonObject 树的 json 文件,并且可以根据需要对其进行操作。 使用:
JsonObject.get(<MemberName>);
JsonObject.add(String <propertyName>, JsonElement <value>);
JsonObject.addProperty(String <propertyName>, Number/String/Boolean/Char <value>);
, ETC。
无论何时完成,您都可以通过OutputStream
或您喜欢的任何方式将其写入您的 json 文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.