问题描述
我正在尝试生成一个 XML 文件并将其保存在 /WEB-INF/pages/
中.
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));
在我的本地机器上作为应用程序运行时它运行良好 (C:\Users\userName\Desktop\Source\MyProject\src\main\webapp\WEB-INF\pages\myFile.xml).代码>
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.FileNotFoundExceptionC:\project\eclipse-jee-luna-R-win32-x86_64\eclipse\src\main\webapp\WEB INF\pages\myFile.xml
我也尝试了 getServletContext().getRealPath()
,但它在我的服务器上返回 null
.有人可以帮忙吗?
I tried getServletContext().getRealPath()
as well, but it's returning null
on my server. Can someone help?
推荐答案
从不在 Java EE Web 应用程序中使用相对本地磁盘文件系统路径,例如 new File("filename.xml")
.如需深入解释,另请参阅getResourceAsStream() vs FileInputStream.
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.
从不使用 getRealPath()
以获取写入文件的位置.有关深入的解释,另请参阅 什么是servletcontext.getRealPath("/") 的意思是什么时候使用它.
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.
永远不要将文件写入部署文件夹.更深入的解释,另见推荐的保存方式在 servlet 应用程序中上传文件.
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");
// ...
或在多种方式之一中进行配置:
File folder = new File(System.getProperty("xml.location"));
File result = new File(folder, "filename.xml");
// ...
或者利用容器-托管临时文件夹:
File folder = (File) getServletContext().getAttribute(ServletContext.TEMPDIR);
File result = new File(folder, "filename.xml");
// ...
或者利用操作系统管理的临时文件夹:
File result = File.createTempFile("filename-", ".xml");
// ...
另一种方法是使用(嵌入式)数据库或 CDN 主机(例如 S3).
The alternative is to use a (embedded) database or a CDN host (e.g. S3).
- 在 servlet 中保存上传文件的推荐方式申请
- 在基于 servlet 的应用程序中如何放置以及如何读取配置资源文件?
- 简单的方法保留有关重新部署 Java EE 7 Web 应用程序的数据
- 在应用服务器上限时存储 PDF 并使其可供下载
- servletcontext.getRealPath("/") 意思是我应该什么时候使用它
- getResourceAsStream() 与 FileInputStream
这篇关于如何在基于 servlet 的 Web 应用程序中临时保存生成的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!