0

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.

Chamila Wijayarathna
  • 1,815
  • 5
  • 30
  • 54
  • Take a look at this post may helps you : http://stackoverflow.com/questions/4340653/file-path-to-resource-in-our-war-web-inf-folder – JHDev Dec 23 '16 at 14:07

2 Answers2

2

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).

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
1

Following code worked,

FileOutputStream output = new FileOutputStream( request.getSession().getServletContext().getRealPath("WEB-INF/classes/data.json"), false);
Chamila Wijayarathna
  • 1,815
  • 5
  • 30
  • 54