1

What is wrong in the below code? in console it is printing proper data but in file there is no data. it is creating 0-byte file.

 JsonObjectBuilder mainObj= Json.createObjectBuilder();
        mainObj.add("delete",delete);
        mainObj.add("update", update);
        mainObj.add("add",add);
       
        String data = mainObj.build().toString();
        System.out.println(data); **//This line printing output**
        BufferedWriter out = new BufferedWriter(new FileWriter("D:/test.json"));
        out.write(data);

Below output is getting printed to console but it is creating 0-byte file.

{"delete":[{"canonicalName":"Amazon"}],"update":[{"canonicalName":"Infosys"},{"canonicalName":"Google HYD"}],"add":[{"canonicalName":"Apple computers"},{"canonicalName":"Microsoft India"},{"canonicalName":"Amazon"},{"canonicalName":"Google India"},{"canonicalName":"CSC"},{"canonicalName":"INFY"}]}
  • 3
    Try calling `out.close()`, which will flush and close the underlying stream . See : https://docs.oracle.com/javase/8/docs/api/java/io/BufferedWriter.html – Arnaud Aug 10 '20 at 13:14
  • 2
    As @Arnaud says, you should `.close()` the `BufferedWriter`. In your case this is not only a side note for good practice, but actually the reason for your problem. – bkis Aug 10 '20 at 13:16

1 Answers1

0

As mentioned in the comments you forgot to close the writer. Instead of out.close() you can also use the new syntax try-with-resources since Java 7:

try (BufferedWriter out = new BufferedWriter(new FileWriter("D:/test.json"))) {
    out.write(data);
}

This will automatically close all Closeables at the end of the try block. Attention: the FileWriter will not be closed by the try-with-resource mechanism as there is no variable created for the FileWriter. Luckily the BufferedWriter.close() will also close the passed FileWriter.

Conffusion
  • 4,335
  • 2
  • 16
  • 28