Search code examples
javaurljarclassloaderembedded-resource

Using resources independent of file location


Here is my directory structure
XYZProject

  • build
  • dist
  • nbproject
  • src

I am working on netbeans.
Now I have a file called ABC.txt
I want to pack this in the jar file.
Now I did the following : made a new folder called Resources under source packages and put the file ABC.txt in that.

XYZProject

-- src  
  |
  -- Resources  
     |
     -- ABC.txt

Now I want to access this file independent of the file location. So I followed some tutorials and did this,

URL url = XYZProject.class.getClassLoader().getResource("Resources/ABC.txt");
String urlStr = urlStr.getFile().replaceAll("%20", " ");
System.out.println(urlStr);
BufferedReader reader;
try {
    reader = new BufferedReader(new FileReader(urlStr)); .....
} catch (FileNotFoundException e) {...}

Now this works when I am running the code through netbeans i.e F6 and tada WORKS!!!
But when try to run the jar, it cannot locate the file. It throws FileNotFoundException
How do I access a text file inside a jar running it via netbeans and via java -jar ?
Also I have no idea why there's a %20 instead of space in the url that I get.

Output running VIA NB

/D:/.../.../.../.../XYZProject/build/classes/Resources/ABC.txt  

Output running VIA java -jar

file:/D:/.../.../.../.../XYZProject/dist/XYZProject.jar!/Resources/ABC.txt

Solution

  • A resource in a Jar is not a File. It must be accessed by URL or InputStream.

    I would probably use URL -> InputStream -> InputStreamReader -> BufferedReader (from memory, not tested).