0

I am trying to load a file that is within a jar file. I try to get the file to load in a BufferedReader. For example:

BufferedReader br = new BufferedReader(new FileReader(fileName)); 

where fileName is my string from the root of the Jar file: something like this "resources/text.txt"

I am having a hard time finding out how to make this happen. Obviously FileReader will not work since it reads from the file system.

Anyone that can help me out?

2
  • Unless there are classes loaded from this jar file the only way I can see is to treat it like an archive. There's an answer on this post stackoverflow.com/questions/3369794/… on how to do it. Commented Jun 16, 2014 at 21:03
  • 1
    Is the jar in question in your classpath? Or is it just some file out in the filesystem? Commented Jun 16, 2014 at 21:05

2 Answers 2

2

Use the classloader to get the resource as a stream.

BufferedReader br = new BufferedReader(new InputStreamReader(MyClass.class.getClassLoader().getResourceAsStream("/resources/text.txt"), "utf-8"); 

Note that you need to specific the correct character encoding for the content.

Sign up to request clarification or add additional context in comments.

3 Comments

Jar that is not relative to the Class its loaded from -OP
Perhaps a clarification is needed. I read that to indicate that the file is not in the same jar as the class being read from, not that the resource is not on the classpath.
Sry it's getting late for me here and I am a bit tired. My English suffers from this. The file is indeed IN the Jar file but not relative to the class (which is in a packet somewhere deeper in the jar file).
1

If you are trying to access a file within the same jar as your running program you should use

final InputStream inputStream = ClassName.class.getResourceAsStream(fileName); 

3 Comments

Tried this method it did not work for me tho :( raised an NullPointerException. Thanks for your effort tho.
This may be because you aren't using the "utf-8" parameter that Brett Okken suggests
Calling getResourceAsStream on the Class will only look for resources relative to the package of the Class used.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.