Traversing files within running jar (in Java 7)

284 views Asked by At

Is it possible to use the new Java 7 NIO file library to traverse a directory tree within a jar in the same way you would on a normal filesystem?

I've got a directory structure I'm reading images from which I'd like to be able to run both in the normal way and also by packaging it as a jar file and running with java -jar.

It seems like the new FileSystem class as well as FileVisitor should be able to achieve this, but there is little documentation on how this can work within a jar. I've tried the following:

private static final FileSystem fileSystem = FileSystems.getDefault();
public static final String workingDir = System.getProperty("user.dir");
Files.walkFileTree(fileSystem.getPath(workingDir, "\res\training\"), new FileVisitor<Path>() {
    ...
    });

This works fine for running from an IDE or by command-line, but when packaged as a jar gives errors similar to:

Exception in thread "main" java.lang.Error:
java.nio.file.NoSuchFileException: C:\Users\rest of path\jar_folder\res\training at util.Main.(Main.java:47) Caused by: java.nio.file.NoSuchFileException: C:\Users\rest of path\jar folder\res\training

Evidently it is attempting to find the files in the directory the jar is running in, rather than inside the jar itself.

0

There are 0 answers