【问题标题】:Confused on getting the path for writing a text file using a Servlet对使用 Servlet 获取写入文本文件的路径感到困惑
【发布时间】:2017-08-04 07:58:35
【问题描述】:

我的 Eclipse 中有以下项目结构。

我在 servlet 中的代码如下。

File entityFile = new File(getServletContext().getContextPath() + "/EntityList/entities.txt");
FileWriter fout = new FileWriter(entityFile);
fout.write("The Content");
fout.close();

这里基本上我正在尝试写入/EntityList/entities.txt 上的可用文件,但是当我运行它时,我得到如下异常。

严重:Servlet.service() 用于 servlet [com.luis.servlets.WriteEntityToAFile] 在上下文中的路径 [/LUISWebUI] 抛出异常 java.io.FileNotFoundException: \LUISWebUI\EntityList\entities.txt(系统找不到路径 指定)

我知道我走错了路,有人可以帮我指明正确的方向吗。

更新

为混乱道歉。

我正在将一些数据从 jsp 发送到 servlet 以写入 entities.txt 文件。我能够在 servlet 中捕获它(通过 sysout 进行交叉检查)。

【问题讨论】:

  • 这个/EntityList/entities.txt在部署的服务器上的什么位置?
  • EntitiesList 放入 WebContent` 文件夹并使用 InputStream stream = getServletContext().getResourceAsStream("/EntitiesList/entities.txt");
  • @Ramanlfc,那么我将如何写入entities.txt,抱歉造成混淆,更新了我的问题。

标签: java eclipse servlets


【解决方案1】:

首先我认为你有一个错字问题,试试/EntitiesList/entities.txt 而不是/EntityList/entities.txt

另外,例如,将/EntitiesList/entities.txt 移动到/WEB-INF/ 下,以便您的servlet 类可以访问它。

你可以阅读更详细的解释in this SO answer

编辑:

关于写入文件:您的应用程序将被打包在一个WAR 文件中,因此您将无法对其进行写入,只能从中读取(有关此here 的更多信息)。

但是您可以使用这种方式直接在 WAR 外部创建文件并使用此位置来编写您的内容(在此之前,请确保您拥有适当的权限):

File entityFile = new File(getServletContext().getContextPath() + "entities.txt");
FileWriter fOut = new FileWriter(entityFile);
fOut.write("The Content");
fOut.close();

或者如果你也想要这个目录,你必须执行一些额外的步骤,首先创建它,然后在其中指定你要写入的文件名:

 File entityFolder = new File(getServletContext().getContextPath() + "EntitiesList");
 entityFolder.mkdir();
 File entityFile = new File(entityFolder, "entities.txt");
 FileWriter fOut = new FileWriter(entityFile);
 fOut.write("The Content");
 fOut.close();

【讨论】:

  • 我将如何写到entities.txt,很抱歉造成混乱,更新了我的问题。
  • 这个东西还是给我同样的文件找不到异常,把它移到WEB-INF,更新的路径是File entityFile = new File(getServletContext().getContextPath() + "/WEB-INF/EntitiesList/entities.txt");
【解决方案2】:
  1. 首先在您的路径中存在拼写错误
  2. 其次,您应该使用 getResourceAsStream() 来加载文件以进行写入。

代码示例:

  InputStream input = getServletContext().
                              getResourceAsStream("/WEB-INF/EntityList/entities.txt");

  Files.copy(InputStream input , Path target) 
  //Or Files.copy(Path source, OutputStream out)

使用FileInputStream似乎更容易,但使用ResourceStream更好。
阅读这里https://stackoverflow.com/a/2161583/8307755
https://stackoverflow.com/a/2308224/8307755

【讨论】:

  • 我正在写入被引用为输入的文件(根据您的代码),我该怎么做?抱歉造成混淆,更新了我的问题。
猜你喜欢
  • 1970-01-01
  • 2013-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-18
  • 2012-05-03
  • 1970-01-01
相关资源
最近更新 更多