Search code examples
javatomcatweb-applicationsfileoutputstreamfile-writing

FileOutputStream paths in java/jsp web application


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.


Solution

  • Following code worked,

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