从类路径加载文件

时间:2013-03-08 15:32:05

标签: spring file classpath

我在java类File file = new File(getFile())中有一行代码:HandleData.java

方法 - getFile()获取属性fileName的值。 fileName通过application_context.xml注入了类的bean部分--HandleData,如下所示:

 <bean id="dataHandler" class="com.profile.transaction.HandleData">
 <property name="fileName" value="DataFile.xml"></property>
 </bean>

我成功构建了项目并检查了DataFile.xml中是否存在WEB-INF/classes。 HandleData.class存在于WEB-INF/classes/com/profile/transacon

但是当我运行它时会抛出filenotfound异常。   如果我注入绝对路径(C:\MyProjectWorkspace\DataProject\target\ProfileService\WEB-INF\classes\DataFile.xml,它会成功找到文件。)。

有人可以帮助确定要注入的正确路径,以便从类路径中获取文件吗?

3 个答案:

答案 0 :(得分:36)

虽然注入File通常是首选方法,但您也可以利用Spring的ResourceLoader动态加载资源。

通常,这就像将ResourceLoader注入Spring bean一样简单:

@Autowired
private ResourceLoader resourceLoader;

然后从类路径加载:

resourceLoader.getResource("classpath:myfile.txt");

答案 1 :(得分:3)

你应该:

<property name="fileName" value="classpath:DataFile.xml" />

它应该以与this answer

类似的org.springframework.core.io.Resource注入

答案 2 :(得分:3)

由于OP只通过spring注入fileName,仍然想通过代码创建文件对象, 您应该使用ClassLoadeer来读取文件

试试这个

InputStream is =  HandleData.class.getClassLoader().getResourceAsStream(getFile()));

修改

继承代码的剩余部分,阅读文件

BufferedInputStream bf = new BufferedInputStream(is);
DataInputStream dis = new DataInputStream(bf);

while (dis.available() != 0) {
    System.out.println(dis.readLine());
}

修改2

因为你想把它作为文件对象,所以要掌握FileInputStream

试试这个

 FileInputStream fisTargetFile = new FileInputStream(new File(HandleData.class.getClassLoader().getResource(getFile()).getFile()));
相关问题