Java 在获取使用Servlet编写文本文件的路径时感到困惑
我在eclipse中有以下项目结构 我在servlet中的代码如下所示Java 在获取使用Servlet编写文本文件的路径时感到困惑,java,eclipse,servlets,Java,Eclipse,Servlets,我在eclipse中有以下项目结构 我在servlet中的代码如下所示 File entityFile = new File(getServletContext().getContextPath() + "/EntityList/entities.txt"); FileWriter fout = new FileWriter(entityFile); fout.write("The Content"); fout.close(); 这里基本上我试图写入一个文件,该文件位于/EntityLis
File entityFile = new File(getServletContext().getContextPath() + "/EntityList/entities.txt");
FileWriter fout = new FileWriter(entityFile);
fout.write("The Content");
fout.close();
这里基本上我试图写入一个文件,该文件位于/EntityList/entities.txt
,但是当我运行它时,我得到如下异常
File entityFile = new File(getServletContext().getContextPath() + "/EntityList/entities.txt");
FileWriter fout = new FileWriter(entityFile);
fout.write("The Content");
fout.close();
严重:Servlet的Servlet.service()
[com.luis.servlets.WriteEntityToAFile]位于具有路径的上下文中
[/LUISWebUI]引发异常java.io.FileNotFoundException:
\LUISWebUI\EntityList\entities.txt(系统找不到路径
(指定)
我知道我走错了路,谁能帮我找到正确的方向
更新
为这一混乱道歉
我将一些数据从jsp发送到servlet,以写入
entities.txt
文件。我能够在servlet中捕获它(通过执行sysout进行交叉检查)。首先,我认为您有打字问题,请尝试/EntitiesList/entities.txt
而不是/EntityList/entities.txt
此外,例如,将/EntitiesList/entities.txt移动到/WEB-INF/
下,以便您的servlet
类可以访问它
你可以阅读更详细的解释
编辑:
关于写入文件:您的应用程序将打包在WAR
文件中,因此您将无法写入,只能从中读取(更多信息)
但您可以使用这种方式直接在WAR之外创建一个文件,并使用此位置编写内容(在此之前,请确保您拥有适当的权限):
或者,如果还需要该目录,则必须执行一些附加步骤,首先创建该目录,然后在其中指定要写入的文件名:
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();
首先,您的路径中存在输入错误
其次,应该使用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更好。
在这里阅读
此/EntityList/entities.txt
位于部署的服务器上的何处?将EntityList
放入WebContent`文件夹中,并使用InputStream=getServletContext().getResourceAsStream(“/EntityList/entities.txt”)@Ramanlfc,那么我将如何写入entities.txt,很抱歉造成混淆,更新了我的问题。我正在写入作为输入的文件(根据您的代码),我该如何操作?很抱歉造成混淆,更新了我的问题。我将如何写入entities.txt,很抱歉造成混淆,更新了我的问题。这个东西仍然给我相同的文件未找到异常,将其移动到WEB-INF
,更新的路径是file entityFile=new file(getServletContext().getContextPath()+“/WEB-INF/EntitiesList/entities.txt”)代码>