Announcement Announcement Module
No announcement yet.
File not found exception while trying to read a txt file from jar Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • 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());;
    return FileUtils.readFileToString(file);

    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.


  • #2
    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, 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 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.


    • #3
      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!!