1

I have a jar file, say archive1.jar, resides in /home/ext/libs. This has a couple of classes, and also a text file (data.txt) at the root of the hierarchy of the jar. One of the classes of this jar (say Data.java) reads the file to initiate some internal data structure.

Now, the archive1.jar is included as a library of another program, called Parsing, which is executed in a completely different directory /home/progs (archive1.jar is specified in the classpath of the execution command of the program).

The problem I am facing is that now Data.java cannot understand the path of data.txt anymore, because it assumes that data.txt resides in /home/progs instead of being inside archive1.jar in /home/ext/libs.

My question is what change should I make inside Data.java in order for it to understand that the data.txt is inside the archive1.jar? In short, how to make Data.java be able to read data.txt inside archive1.jar, no matter where the calling program is.

Note: In thread Java resource as file, thing was a bit different, and also there was no answer to how to read the file inside the jar. One said it might be impossible.

Extreme Coders
  • 3,195
  • 2
  • 33
  • 49
Simo
  • 1,906
  • 5
  • 22
  • 40
  • could we see some code? – Dillon Burton Jun 19 '13 at 01:19
  • I looked into "Java resources as file" thread but did not really find an adequate answer. Here is the code. Inside Data.java, there is BufferedReader br = new BufferedReader(new FileReader("data.txt")); This Data.java is inside archive1.jar, which in turn is in /home/ext/libs – Simo Jun 19 '13 at 01:24
  • How can you not find an adequate answer when that Q (and things that are dups of it) tell you exactly what to do, and you're not doing it, at all? – Brian Roach Jun 19 '13 at 01:44
  • http://stackoverflow.com/questions/574809/load-a-resource-contained-in-a-jar I think what you're looking for is getResourceAsStream. – Nicolas Couture-Grenier Jun 19 '13 at 01:58
  • `java -cp archive1.jar;other.jar our.com.Main` Either that or specify by relative path in the manifest. – Andrew Thompson Jun 19 '13 at 02:46

1 Answers1

2

The way to access resource files inside JAR archives is by using getClass().getResourceAsStream() . Using this ensures that the resource is loaded from the archive not from the filesystem. For example if you have data.txt in the same location as Data.java within the JAR archive, then you would access the data.txt in this way

InputStream is=getClass().getResourceAsStream("data.txt");

Once you have got an InputStream to the resource proceed with the way you like.

Extreme Coders
  • 3,195
  • 2
  • 33
  • 49