我正在尝试生成一个 XML 文件并将其保存在 /WEB-INF/pages/
中。
下面是我使用相对路径的代码:
File folder = new File("src/main/webapp/WEB-INF/pages/");
StreamResult result = new StreamResult(new File(folder, fileName));
在我的本地计算机上作为应用程序运行时工作正常(C:\Users\userName\Desktop\Source\MyProject\src\main\webapp\WEB-INF\pages\myFile.xml)。
但是在服务器上部署并运行时,会抛出以下异常:
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
我也尝试了 getServletContext().getRealPath()
,但它在我的服务器上返回 null
。有人可以帮忙吗?
最佳答案
切勿在 Java EE Web 应用程序中使用相对本地磁盘文件系统路径,例如 new File("filename.xml")
。有关深入的解释,另请参阅 getResourceAsStream() vs FileInputStream .
切勿使用 getRealPath()
来获取写入文件的位置。有关深入的解释,另请参阅 What does servletcontext.getRealPath("/") mean and when should I use it .
永远不要将文件写入部署文件夹。有关深入的解释,另请参阅 Recommended way to save uploaded files in a servlet application .
始终将它们写入预定义绝对路径上的外部文件夹。
硬编码:
File folder = new File("/absolute/path/to/web/files"); File result = new File(folder, "filename.xml"); // ...
或在 one of many ways 中配置:
File folder = new File(System.getProperty("xml.location")); File result = new File(folder, "filename.xml"); // ...
或者利用container-managed temp folder :
File folder = (File) getServletContext().getAttribute(ServletContext.TEMPDIR); File result = new File(folder, "filename.xml"); // ...
或者利用OS-managed temp folder :
File result = File.createTempFile("filename-", ".xml"); // ...
另一种方法是使用(嵌入式)数据库或 CDN 主机(例如 S3)。
另请参阅:
- 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
关于servlets - 如何在基于 servlet 的 Web 应用程序中临时保存生成的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35558321/