Feb 25th, 2011, 06:57 PM
File not found exception while trying to read a txt file from jar
I have a requirement where I need to read a file from a jar.
In my xml file in the jar, I have:
<bean id="messageService" class="com.service.MessageServiceImpl">
<property name="fileResource" value="classpath:com/content/welcome.txt"/>
And in the MessageServiceImp I try to do this in a method to return the file as string and it doesnt seem to work:
Resource resource = this.fileResource;
File file = new File(resource.getURL().getFile());;
This works from my eclipse where the project is not a jar. But I'm not able to get this working when the project is jar.
I get a FileNotFoundException. Any idea what could be wrong.
Feb 26th, 2011, 06:57 AM
Since the text file is inside the JAR, the operating system cannot read it (like any normal file, anyway), so when you create a new java.io.File, you get an exception.
You have two possibilities:
a) Store the file in an external location - next to the JAR, in a known directory etc. You can then use the java.io.File API.
b) Work with the file in the JAR as an InputStream (the Spring Resource class supports this). This is my recommended option since I see that you use the file to read it as a String and an InputStream can easily be used for this.
Feb 26th, 2011, 10:51 AM
Thanks!!. I went for option 2. (Option 1 had worked for me. But I wanted the file to be part of my jar.)
Thanks for your help!!