Sayem Sayem - 4 years ago 248
Java Question

How to write into json file without overriding in Java

I have a method which store data to json file using ObjectMapper.Its fine.But When i try to add new data it clears previous data.Is their anyway to write without clear file.

public String addnews(@ModelAttribute("SpringWeb")Story story,
ModelMap model,HttpServletRequest request) {
ObjectMapper mapper = new ObjectMapper();
try{
String phyPath = request.getSession().getServletContext().getRealPath("/");
String filepath = phyPath + "resources/" + "data.json";
File file = new File(filepath);
if (!file.exists()) {
System.out.println("pai nai");
file.createNewFile();
}
mapper.writeValue(file, story);
mapper.writerWithDefaultPrettyPrinter().writeValueAsString( story);
System.out.println("Done");
}
catch (IOException e) {
e.printStackTrace();
}

return "result";
}

Answer Source

You can use java.nio.file.Files library, for example:

// Create JSON
final String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(story);

// Content is appended (due to StandardOpenOption.APPEND)
Files.write(new File(filepath).toPath(), Arrays.asList(json), StandardOpenOption.APPEND);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download