【问题标题】:How to save generated file temporarily in servlet based web application如何在基于 servlet 的 Web 应用程序中临时保存生成的文件
【发布时间】:2015-09-24 03:52:54
【问题描述】:

我正在尝试生成一个 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 服务器中?

标签: servlets relative-path realpath


【解决方案1】:

从不在 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)。

另见:

【讨论】:

  • 谢谢 :) 我明白了 :)
  • 不允许您将文件系统与 Java EE 一起使用的原因是因为它被设计为在多个主机上透明地工作。您的代码在写入时可能在一台主机上运行,​​而在尝试读回结果时可能在另一台主机上运行。
【解决方案2】:

随便用

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

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

【讨论】:

    猜你喜欢
    • 2012-06-20
    • 1970-01-01
    • 1970-01-01
    • 2014-01-24
    • 1970-01-01
    • 2023-03-15
    相关资源
    最近更新 更多