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?

Natan Streppel
  • 5,759
  • 6
  • 35
  • 43
c-pid
  • 122
  • 1
  • 9
  • 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 http://stackoverflow.com/questions/3369794/how-to-a-read-file-from-jar-in-java#answer-13030711 on how to do it. – ug_ Jun 16 '14 at 21:03
  • 1
    Is the jar in question in your classpath? Or is it just some file out in the filesystem? – Kenster Jun 16 '14 at 21:05

2 Answers2

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.

Brett Okken
  • 6,210
  • 1
  • 19
  • 25
  • *Jar that is not relative to the Class its loaded from* -OP – ug_ Jun 16 '14 at 21:04
  • 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. – Brett Okken Jun 16 '14 at 21:05
  • 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). – c-pid Jun 16 '14 at 21:08
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);
Jonathan Leitschuh
  • 822
  • 1
  • 8
  • 29