How to save generated file temporarily in servlet based web application
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:
- Recommended way to save uploaded files in a servlet application
- Where to place and how to read configuration resource files in servlet based application?
- Simple ways to keep data on redeployment of Java EE 7 web application
- Store PDF for a limited time on app server and make it available for download
- What does servletcontext.getRealPath("/") mean and when should I use it
- getResourceAsStream() vs FileInputStream