File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes How to read a file packaged in a jar file Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "How to read a file packaged in a jar file" Watch "How to read a file packaged in a jar file" New topic

How to read a file packaged in a jar file

Rajani Gummadi
Ranch Hand

Joined: Dec 17, 2010
Posts: 48
Hi All,

I have this embarssing problem, in reading a file which is packaged in a jar file.

I have a project in eclipse, say sample. My project structure is as below

Under this setup, I can simply access the file in, as below

and it works like a gem .

Now I exported this project as a runnable jar file and when I looked into the jar file, is missing, as expected.

So, in order to have this file available in jar file, I moved into src folder. But this time, FileReader fails, as it could not find the file for apparent reasons.

Exception Caused: The property file could not be resolv
ed file:\C:\Projects\Sample.jar!\ (The filename, directory name, or volume label syntax is incorrect)
at Method)

I know that the way, I'm accessing the file in FileReader is the problem, but not able to fix it. How can access the file when that is the part of the jar file, to which class belongs. This is apparently the most common way of doing where everything is jar'ed together.
Wouter Oet
Saloon Keeper

Joined: Oct 25, 2008
Posts: 2700

That is because once it is packaged in a jar it is no longer a file. You can load resources with a class object which will provide the resource as a stream or URL.

"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
I agree. Here's the link:
subject: How to read a file packaged in a jar file
jQuery in Action, 3rd edition