fsteeg.com | notes | tags

∞ /notes/accessing-files-in-jars | 2007-02-23 | java

Accessing files in Jars

Cross-posted to: https://fsteeg.wordpress.com/2007/02/23/accessing-files-in-jars/

Just as a small note, as I was only hardly finding help on this anywhere: If you are trying to access files in a folder, which is bundled inside a Jar file and you try to access them as anyone would: by instantiating a File for the directory - via getResource("directory/") - and then getting all the files: it doesn't work, you can't access a folder in a Jar, you will have to iterate over all the JarEntries, and check for each if it is in the directory (or check its name), like this:

JarFile jarFile = new JarFile("some.jar");
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
  JarEntry e = entries.nextElement();
  if (e.getName().endsWith("lst")) {
    InputStream inputStream = jarFile.getInputStream(e);
    Scanner s = new Scanner(inputStream);
    while (s.hasNextLine()) {
      String nextLine = s.nextLine();     //...

On the other hand, if you need to access only a single file, the way to go is using the getResourceAsStream() method in Class and reading the stream.