Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

loading a file from classpath

I have a line of code that is : File file = new File(getFile()) in a java class HandleData.java

Method - getFile() takes the value of the property fileName. And fileName is injected through application_context.xml with a bean section of the class - HandleData as below:

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

I build the project successfully and checked that - DataFile.xml is present in WEB-INF/classes. And the HandleData.class is present in WEB-INF/classes/com/profile/transacon

But when I run it it throws me filenotfound exception. If I inject the absolute path (C:\MyProjectWorkspace\DataProject\target\ProfileService\WEB-INF\classes\DataFile.xml it finds the file successfully.).

Could someone help in figuring out the proper path to be injected so that the file is taken from the classpath ?

like image 905
Steer360 Avatar asked Mar 08 '13 15:03

Steer360


1 Answers

While injecting a File is generally the preferred approach, you can also leverage Spring's ResourceLoader for dynamic loading of resources.

Generally this is as simple as injecting the ResourceLoader into your Spring bean:

@Autowired
private ResourceLoader resourceLoader;

Then to load from the classpath:

resourceLoader.getResource("classpath:myfile.txt");
like image 147
helmy Avatar answered Sep 30 '22 20:09

helmy