How to save generated file temporarily in servlet based web application
Asked Answered
R

2

18

I am trying to generate a XML file and save it in /WEB-INF/pages/.

Below is my code which uses a relative path:

File folder = new File("src/main/webapp/WEB-INF/pages/");
StreamResult result = new StreamResult(new File(folder, fileName));

It's working fine when running as an application on my local machine (C:\Users\userName\Desktop\Source\MyProject\src\main\webapp\WEB-INF\pages\myFile.xml).

But when deploying and running on server machine, it throws the below exception:

javax.xml.transform.TransformerException: java.io.FileNotFoundException C:\project\eclipse-jee-luna-R-win32-x86_64\eclipse\src\main\webapp\WEB INF\pages\myFile.xml

I tried getServletContext().getRealPath() as well, but it's returning null on my server. Can someone help?

Reconciliatory answered 6/7, 2015 at 20:51 Comment(1)
Are you generating a WAR file and launch it into a web server like tomcat ?Sawhorse
I
35

Never use relative local disk file system paths in a Java EE web application such as new File("filename.xml"). For an in depth explanation, see also getResourceAsStream() vs FileInputStream.

Never use getRealPath() with the purpose to obtain a location to write files. For an in depth explanation, see also What does servletcontext.getRealPath("/") mean and when should I use it.

Never write files to deploy folder anyway. For an in depth explanation, see also Recommended way to save uploaded files in a servlet application.

Always write them to an external folder on a predefined absolute path.

  • Either hardcoded:

      File folder = new File("/absolute/path/to/web/files");
      File result = new File(folder, "filename.xml");
      // ...
    
  • Or configured in one of many ways:

      File folder = new File(System.getProperty("xml.location"));
      File result = new File(folder, "filename.xml");
      // ...
    
  • Or making use of container-managed temp folder:

      File folder = (File) getServletContext().getAttribute(ServletContext.TEMPDIR);
      File result = new File(folder, "filename.xml");
      // ...
    
  • Or making use of OS-managed temp folder:

      File result = File.createTempFile("filename-", ".xml");
      // ...
    

The alternative is to use a (embedded) database or a CDN host (e.g. S3).

See also:

Illaudable answered 6/7, 2015 at 21:10 Comment(1)
The reason why you are not allowed to use the file system with Java EE is because it is designed to work transparently over several hosts. Your code may run on one host when writing and another when trying to read back the results.Loferski
A
-3

just use

File relpath = new File(".\pages\");

as application cursor in default stay into web-inf folder.

Ashliashlie answered 6/7, 2015 at 21:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.