Tomcat7找不到我的txt文件

时间:2017-05-31 14:22:46

标签: java file servlets tomcat7

我有一个java Web应用程序项目,它包含一个java servlet,然后是一个经典的java文件。 servlet调用java文件中实现的方法。

其中一种方法涉及从文件读取并将该文件的内容放入数组中。但是,在尝试BufferedReader,InputStream和classloader.getResource()之后,我仍然无法让它能够找到txt文件。

在Tomcat目录中,java文件和txt文件位于/ WEB-INF / classes中。所以我不确定为什么它找不到该文件..

有人能告诉我尝试从该文件中读取的最佳方法吗?

提前致谢。

编辑:这是我最近尝试从中读取的尝试,导致FileNotFound异常。

ClassLoader cl = testClass.class.getClassLoader();
File file = new File(cl.getResource("text.txt").getFile());

Scanner sc = new Scanner(file); 

2 个答案:

答案 0 :(得分:0)

你可以试试这个:

File file = new File(ClassLoader.getSystemResource("/path/to/file.txt").getFile());

答案 1 :(得分:0)

没有领先/

ClassLoader cl = testClass.class.getClassLoader(); File file = new File(cl.getResource("text.txt").getFile());

text.txt应该在WEB-INF / classes / ppp / text.txt中,其中ppp是testClass的包路径。

带前导/

ClassLoader cl = testClass.class.getClassLoader(); File file = new File(cl.getResource("/text.txt").getFile());

在类路径(tomcat / lib,WEB-INF / lib,WEB-INF / classes等)上搜索

text.txt。