FileOutputStream paths in java/jsp web application

1.5k views Asked by At

I have a simple java web application with following folder structure.

enter image description here

When I deploy the web app it has data.json file in WEB-INF/classes folder. I need to write data to this file from controller.java class controller package which is in WEB-INF/classes folder.

I tried following code.

FileOutputStream output = new FileOutputStream("..\\data.json", true);
output.write(jsonObject.toJSONString().getBytes());
output.flush();

This doesn't give me any error which suggest that the operation happen in a file somewhere in my computer.

How can I write to the data.json file? I can't give absolute path here.

2

There are 2 answers

0
Chamila Wijayarathna On BEST ANSWER

Following code worked,

FileOutputStream output = new FileOutputStream( request.getSession().getServletContext().getRealPath("WEB-INF/classes/data.json"), false);
4
Joop Eggen On

WEB-INF/classes is for the class-path. Files there should be considered read-only, cacheable resources (getResource, getResourceAsStream).

The HttpRequest.getServletContext().getRealPath("/WEB-INF") can be used, for file system paths.

I suggest using the classes files as template, copied the first time to a real file system path, and then being overwritten.

Use /, not Windows \\.

Use close() and then flush() is not needed.

Use getBytes(StandardCharsets.UTF_8).