在Spring中的构造函数参数中从类路径读取文件时出现FileNotFound异常

时间:2014-02-24 08:33:54

标签: java spring spring-mvc classpath applicationcontext

我在以下位置有一个文件mydoc.txt

C:/Tomcat6.0/webapps/myapp/WEB-INF/classes/document/mydoc.txt

我必须通过构造函数注入获取此文件位置并读取该文件。

public DocumentReader(String path) throws IOException, FileNotFoundException {
BufferedReader reader = new BufferedReader(new FileReader(path));
String line = null;
StringBuilder stringBuilder = new StringBuilder();
while ((line = reader.readLine()) != null) {
  stringBuilder.append(line);
}
String doc = stringBuilder.toString();
}

我已经在applicationContext.xml中配置了文件位置,如下所示。

<bean id="DocumentReader" class="com.myapp.DocumentReader" >
<constructor-arg  value="classpath:document/mydoc.txt"></constructor-arg>
</bean>

但是,我在运行应用程序时遇到了FileNotFound Exception。有没有其他方法可以从这个位置读取文件?

异常

java.io.FileNotFoundException:  classpath:document\mydoc.txt(The filename, directory name, or volume label syntax is incorrect)

1 个答案:

答案 0 :(得分:2)

更改构造函数以使用org.springframework.core.io.Resource而不是String。

如果你的构造函数参数是String类型,那么Spring就像你把它写下来一样插入值。然后,您的FileReader在文件夹mydoc.txt中查找名为classpath:document的文件(在某些操作系统上 - 如窗口 - 甚至不是有效的文件夹名称)

如果你的constructor-argument的类型是Ressource,那么Spring假定你注入的String是一个Spring-Ressource-Path并为你做出解决。