0

How can I write on a file having its URL such as /WebContent/Database/myFile.json from a Servlet?

Constraint: I can't use absolute paths to write on this file.

Additional info: the servlet receives a string as a POST parameter, then her should write this string on a file located in the same servlet context.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
shogitai
  • 1,823
  • 1
  • 23
  • 50
  • Should it be a permanent file or a temporary file? In any case, this answer should contain sufficient hints: http://stackoverflow.com/q/31255366 – BalusC Apr 06 '16 at 18:13

1 Answers1

1

Update It is a very bad idea to write files to the servlets context, see this answer from @BalusC.


Not recommended But here is how you can get the absolute path for this context relative path

ServletContext context = request.getSession().getServletContext();
String relPath = "/WebContent/Database/myFile.json";
String absPath = context.getRealPath(relPath);
Community
  • 1
  • 1
gustf
  • 1,959
  • 13
  • 20