BufferedWriter未能正确写入数据。

huangapple go评论79阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2020年8月10日 21:11:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/63340900.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定