Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (10.2k points)

I would like to read a resource from within my jar like so:

File file;

file = new File(getClass().getResource("/file.txt").toURI());

BufferredReader reader = new BufferedReader(new FileReader(file));

//Read the file

and it works fine when running it in Eclipse, but if I export it to a jar the run it there is an IllegalArgumentException:

Exception in thread "Thread-2"

java.lang.IllegalArgumentException: URI is not hierarchical

and I really don't know why but with some testing I found if I change

file = new File(getClass().getResource("/file.txt").toURI());

to

file = new File(getClass().getResource("/folder/file.txt").toURI());

then it works the opposite (it works in jar but not eclipse).

I'm using Eclipse and the folder with my file is in a class folder.

1 Answer

0 votes
by (46k points)

Rather than trying to address the resource as a File just ask the ClassLoader to return an InputStream for the resource instead via getResourceAsStream:

InputStream in = getClass().getResourceAsStream("/file.txt"); 

BufferedReader reader = new BufferedReader(new InputStreamReader(in));

As continued as the file.txt resource is accessible on the classpath then this approach will serve the same way regardless of whether the file.txt device is in a classes/ directory or inside a jar.

The URI is not hierarchical happens because the URI for a store within a jar file is going to look something like this: 

file:/example.jar!/file.txt. You cannot read the entries within a jar (a zip file) like it was a plain old File.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Oct 17, 2019 in Java by Shubham (3.9k points)
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...