如何在基于servlet的Web应用程序中临时保存生成的文件

18

我正在尝试生成一个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。有人能帮忙吗?


你是否正在生成一个WAR文件并将其部署到像Tomcat这样的Web服务器中? - Nelson G.
2个回答

35
请勿在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
始终将它们写入预定义的绝对路径上的外部文件夹。
  • 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");
      // ...
    

另一种选择是使用嵌入式数据库或CDN主机(例如S3)。

另请参阅:


谢谢 :) 我明白了 :) - sjohnson
1
你不能在Java EE中使用文件系统的原因是它被设计为在多个主机之间透明地工作。当你写代码时,它可能在一个主机上运行,但在尝试读取结果时却在另一个主机上运行。 - Thorbjørn Ravn Andersen

-3

只需使用:

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

作为应用程序光标,默认停留在web-inf文件夹中。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接