Servlet中读取txt文本文件路径问题

在进行javaweb开发中,遇到了一个问题,就是Servlet读取webcontent下的文本文件路径问题,会出现系统找不到文件的各种错误,经过查找问题,发现原来是由于这个项目部署在tomcat上之后,文件的目录结构会发生相应的一些变化,所以说使用常规的获取相对或绝对路径的方式在这个照常使用会导致运行之后,系统提示找不到文件路径的一些错误提示。
下面对如何在servlet中读取WEB-INF下的我存放的txt文件进行记录。

下图为项目路径,而这里要实现的便是使用teacherProduce这一个Servlet来读取WEB-INF目录下的teacher1.txt文件。
在这里插入图片描述
在这里说明一些获取文件路径的问题
常规的相对路径在这里无效,在tomcat上部署后目录结构变了
要使用getServletContext().getRealPath 来获取文件的路径。

1
String pathname = this.getServletContext().getRealPath("/txt/teacher1.txt");

需要注意的是:getServletContext().getRealPath只能在servlet中使用。

完整代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
public class teacherProduce extends HttpServlet {

private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

request.setCharacterEncoding("UTF-8");
//读取文件
String content = null;


String pathname = this.getServletContext().getRealPath("/txt/teacher1.txt");

String encoding = "UTF-8";
File file = new File(pathname);
System.out.println(file);

BufferedReader br = null;
try {
InputStreamReader reader = new InputStreamReader(new FileInputStream(file));
br = new BufferedReader(reader);
String line = "";
while ((line = br.readLine()) != null) {
System.out.println(line);
content = content +line;
}

} catch (Exception e) {
e.printStackTrace();
}finally{
if(br != null){
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}

}

request.setAttribute("content", content);

request.getRequestDispatcher("/personProduce/personProduce.jsp").forward(request, response);

}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}


}

本文标题:Servlet中读取txt文本文件路径问题

文章作者:雷凯博

发布时间:2018年02月10日 - 13:02

最后更新:2021年05月16日 - 19:05

原始链接:http://yoursite.com/2018/02/10/2018-02-10-Servlet%E4%B8%AD%E8%AF%BB%E5%8F%96txt%E6%96%87%E6%9C%AC%E6%96%87%E4%BB%B6%E8%B7%AF%E5%BE%84%E9%97%AE%E9%A2%98/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

坚持原创技术分享,您的支持将鼓励我继续创作!
-------------本文结束感谢您的阅读-------------
0%