Results 1 to 3 of 3

Thread: File not found exception while trying to read a txt file from jar

  1. #1
    Join Date
    Oct 2009
    Posts
    8

    Default File not found exception while trying to read a txt file from jar

    Hi,

    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"/>
    </bean>


    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.

    Thanks

  2. #2

    Default

    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.

  3. #3
    Join Date
    Oct 2009
    Posts
    8

    Default

    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!!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •