0

How to get the directory inside the jar?

Let's say I have a jar called foo.jar, how can I make the jar be able to access a file that's like this foo.jar!/text.txt, whereas the class is like foo.jar!/randomPackage/Main.class?

I'm able to do that while still in eclipse, but then when I export the program into a jar, it doesn't work.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
martin
  • 1,007
  • 2
  • 16
  • 32

2 Answers2

2

You need to use, e.g., java.lang.Class.getResourceAsStream() to access the file. That will work either inside a jar or on the filesystem.

Ernest Friedman-Hill
  • 80,601
  • 10
  • 150
  • 186
  • Right, though how can I get the parent directory, because this gets me the directory of the class? – martin May 15 '13 at 20:24
  • Prefix the String you pass with `/`, to reference the root of the jar. – Sotirios Delimanolis May 15 '13 at 20:26
  • 1
    @Martin, there *is* no directory in a jar file -- files just have path names associated with them -- so it doesn't make sense to ask for access to it. There's no way to list the files in a jar file without opening it using something like `ZipInputStream`. But note that depending on the argument you pass it (read the Javadoc), the `getResource()` family of methods can find files "next to" class files, or at the root of a classpath entry, or indeed, anywhere along the classpath, inside a jar or out. – Ernest Friedman-Hill May 15 '13 at 20:41
0

You have 2 main options.

  1. this.getClass().getClassLoader().getResourceAsStream("some/pkg/resource.properties");

  2. this.getClass().getResourceAsStream.("/some/pkg/resource.properties");

I just posted this more full post on it recently, getResourceAsStream returns null

Community
  • 1
  • 1
greedybuddha
  • 7,488
  • 3
  • 36
  • 50