File writer fails to write to existing json?

90 Views Asked by At

File writer fails to write to existing json ?

I definitely get the value but write buffer is null during the whose process.

How to fix this issue ? No error or exception is caught.

I have tried using different types of Writer too.


     String path = resourceHelper.getFilePath(DOCUMENT_PATH2);
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        BufferedWriter writer = new BufferedWriter(new FileWriter(path));
        writer.write(gson.toJson(documentToSave));
        writer.flush();
        writer.close();

OR


Files.write(Paths.get(path), new Gson().toJson(documentToSave).getBytes(StandardCharsets.UTF_8));

1

There are 1 best solutions below

2
John Williams On BEST ANSWER

Try this:

    String path = resourceHelper.getFilePath(DOCUMENT_PATH2);
    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    BufferedWriter writer = new BufferedWriter(new FileWriter(path));
    String json = gson.toJson(documentToSave);
    System.out.println(“json: ” + json);
    writer.write(json, 0, json.size());
    writer.flush();
    writer.close();