Search code examples
urlservletsfile-iofilestream

How to write on file having its url from a servlet


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.


Solution

  • 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);