我正在尝试生成一个 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
I tried getServletContext().getRealPath()
也一样,但它正在回归null
在我的服务器上。有人可以帮忙吗?
Never在 Java EE Web 应用程序中使用相对本地磁盘文件系统路径,例如new File("filename.xml")
。有关深入的解释,另请参阅getResourceAsStream() 与 FileInputStream https://stackoverflow.com/questions/2308188/getresourceasstream-vs-fileinputstream.
Never use getRealPath()
目的是获取写入文件的位置。有关深入的解释,另请参阅servletcontext.getRealPath("/") 是什么意思以及何时应该使用它 https://stackoverflow.com/questions/12160639/what-does-servletcontext-getrealpath-mean-and-when-should-i-use-it.
Never无论如何,将文件写入部署文件夹。有关深入的解释,另请参阅在 servlet 应用程序中保存上传文件的推荐方法 https://stackoverflow.com/questions/18664579/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");
// ...
-
或者配置在多种方法之一 https://stackoverflow.com/a/18664715/157882:
File folder = new File(System.getProperty("xml.location"));
File result = new File(folder, "filename.xml");
// ...
-
或者利用容器管理的临时文件夹 http://docs.oracle.com/javaee/7/api/javax/servlet/ServletContext.html#TEMPDIR:
File folder = (File) getServletContext().getAttribute(ServletContext.TEMPDIR);
File result = new File(folder, "filename.xml");
// ...
-
或者利用操作系统管理的临时文件夹 https://docs.oracle.com/javase/8/docs/api/java/io/File.html#createTempFile-java.lang.String-java.lang.String-:
File result = File.createTempFile("filename-", ".xml");
// ...
另一种方法是使用(嵌入式)数据库或 CDN 主机(例如 S3)。
也可以看看:
- 在 servlet 应用程序中保存上传文件的推荐方法 https://stackoverflow.com/questions/18664579/recommended-way-to-save-uploaded-files-in-a-servlet-application
- 在基于 servlet 的应用程序中,配置资源文件应该放在哪里以及如何读取? https://stackoverflow.com/questions/2161054/where-to-place-and-how-to-read-configuration-resource-files-in-servlet-based-app/
- 在重新部署 Java EE 7 Web 应用程序时保留数据的简单方法 https://stackoverflow.com/questions/27804742/simple-ways-to-keep-data-on-redeployment-of-java-ee-7-web-application/
- 在应用程序服务器上存储 PDF 一段有限的时间并可供下载 https://stackoverflow.com/questions/25430677/store-pdf-for-a-limited-time-on-app-server-and-make-it-available-for-download/
- servletcontext.getRealPath("/") 是什么意思以及何时应该使用它 https://stackoverflow.com/questions/12160639/what-does-servletcontext-getrealpath-mean-and-when-should-i-use-it
- getResourceAsStream() 与 FileInputStream https://stackoverflow.com/questions/2308188/getresourceasstream-vs-fileinputstream
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)