英文:
BufferedWriter is not writing data properly
问题
The issue in the provided code is that it is creating a 0-byte file.
英文:
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"}]}
答案1
得分: 0
正如评论中所提到的,您忘记关闭写入器。
除了使用 out.close() 外,您还可以使用自 Java 7 起的新语法 try-with-resources:
try (BufferedWriter out = new BufferedWriter(new FileWriter("D:/test.json"))) {
out.write(data);
}
这将在 try 块结束时自动关闭所有 Closeables。
注意:FileWriter 不会被 try-with-resource 机制关闭,因为没有为 FileWriter 创建变量。幸运的是,BufferedWriter.close() 也会关闭传递的 FileWriter。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论