-3

Hey so I'm trying to write json files and I can't seem a source anywhere explaining why the whole file gets overridden and gets back to square one, this is the code I happen to be using.

            JSONObject j = new JSONObject();
        j.put("name", member.getUser().getName());

        JSONObject group = new JSONObject();
        group.put(String.valueOf(Math.random()), j);

        String fileName = "test.json";
        try (FileWriter file = new FileWriter(fileName)) {

            file.write(group.toString());
            file.flush();

        } catch (IOException e) {
            e.fillInStackTrace();
        }

My JSON file gets written like this,

{"0.027601526266715193":{"name":"Keurig"}}

But if I run it again it does not add another group how I want it to it just overrides the file, this is how I wanted it to be.

{"0.027601526266715193":{"name":"Keurig"}, "0.02015264243212141":{"name":"Keurig"}}
Keurig
  • 13
  • 4
  • You're creating and initializing a new "j", then adding it to a new "group", finally printing the new "group" object. *SO WHERE ARE YOU READING THE PREVIOUS OBJECT? AND WHERE ARE YOU APPENDING THE NEW "GROUP" TO IT???* – paulsm4 Jul 17 '20 at 04:41
  • Read the [documentation](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/io/FileWriter.html). FileWriter​(File file, boolean append) – MarsAtomic Jul 17 '20 at 04:41
  • @ScaryWombat - Java FileWriter "append" was my first thought. But the OP will get `{"0.123":{"name":"Keurig"}}{"0.345":{"name":"Keurig"}}`, which isn't legal JSON. He needs to 1) read the original JSON into a JSON object, 2) append the new data to that object, and finally 3) write the newly updated object (presumably *WITHOUT* "append" mode). He definitely needs a 3rd JSON object (besides "j" and "group"); presumably a JSONArray. – paulsm4 Jul 17 '20 at 04:45
  • @Keurig: I think you mean ["overwritten"](https://en.wikipedia.org/wiki/Overwriting_(computer_science)), not ["overridden"](https://www.techopedia.com/definition/24010/overriding) – paulsm4 Jul 17 '20 at 04:46
  • Thank you @MarsAtomic sorry I must have skimmed over that part in the documentation – Keurig Jul 17 '20 at 05:05
  • @Keurig Before you go thanking me, are you sure you're looking to nest your newly written JSON objects within JSON that's already in your file? If so, that's a little odd, and no, opening the file in append mode won't get you what you want, as per comments from other posters, above. You're going to get a stray curly brace instead of a comma unless you control for those things by altering the file yourself. – MarsAtomic Jul 17 '20 at 05:12

1 Answers1

0

You need below code to solve your problem:

    JSONObject json;
    String fileName= "test.json";
    File f = new File(fileName);
    JSONObject j = new JSONObject();
    j.put("name", member.getUser().getName());
    if (f.exists()){
        InputStream is = new FileInputStream(fileName);
        String jsonTxt;
        try (Scanner scanner = new Scanner(is, StandardCharsets.UTF_8.name())) {
            jsonTxt = scanner.useDelimiter("\\A").next();
        }
        json = new JSONObject(jsonTxt);
    }else {
        json = new JSONObject();
    }
    json.put(String.valueOf(Math.random()), j);
    try (FileWriter file = new FileWriter(fileName)) {
        file.write(json.toString());
        file.flush();

    } catch (IOException e) {
        e.fillInStackTrace();
    }
Ashish Karn
  • 1,127
  • 1
  • 9
  • 20