Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a directory inside a .jar

I am trying to access a directory inside my jar file. I want to go through every of the files inside the directory itself. I tried, for example, using the following:

URL imagesDirectoryURL=getClass().getClassLoader().getResource("Images");

if(imagesFolderURL!=null)
{
    File imagesDirectory= new File(imagesDirectoryURL.getFile());
}

If I test this applet, it works well. But once I put the contents into the jar, it doesn't because of several reasons. If I use this code, the URL always points outside the jar, so I have to put the Images directory there. But if I use new File(imagesDirectoryURL.toURI());, it doesn't work inside the jar because I get the error URI not hierarchical. I am sure the directory exists inside the jar. How am I supposed the get the contents of Images inside the jar?

like image 433
Ivorius Avatar asked Apr 29 '11 09:04

Ivorius


2 Answers

Here is a solution which should work given that you use Java 7... The "trick" is to use the new file API. Oracle JDK provides a FileSystem implementation which can be used to peek into/modify ZIP files, and that include jars!

Preliminary: grab System.getProperty("java.class.path", "."), split against :; this will give you all entries in your defined classpath.

First, define a method to obtain a FileSystem out of a classpath entry:

private static final Map<String, ?> ENV = Collections.emptyMap();

//

private static FileSystem getFileSystem(final String entryName)
    throws IOException
{
    final String uri = entryName.endsWith(".jar") || entryName.endsWith(".zip"))
        ? "jar:file:" + entryName : "file:" + entryName;
    return FileSystems.newFileSystem(URI.create(uri), ENV);
}

Then create a method to tell whether a path exists within a filesystem:

private static boolean pathExists(final FileSystem fs, final String needle)
{
    final Path path = fs.getPath(needle);
    return Files.exists(path);
}

Use it to locate your directory.

Once you have the correct FileSystem, use it to walk your directory using .getPath() as above and open a DirectoryStream using Files.newDirectoryStream().

And don't forget to .close() a FileSystem once you're done with it!

Here is a sample main() demonstrating how to read all the root entries of a jar:

public static void main(final String... args)
    throws IOException
{
    final Map<String, ?> env = Collections.emptyMap();
    final String jarName = "/opt/sunjdk/1.6/current/jre/lib/plugin.jar";
    final URI uri = URI.create("jar:file:" + jarName);
    final FileSystem fs = FileSystems.newFileSystem(uri, env);
    final Path dir = fs.getPath("/");
    for (Path entry : Files.newDirectoryStream(dir))
        System.out.println(entry);
}
like image 53
fge Avatar answered Sep 28 '22 10:09

fge


Paths within Jars are paths, not actual directories as you can use them on a file system. To get all resources within a particular path of a Jar file:

  • Gain an URL pointing to the Jar.
  • Get an InputStream from the URL.
  • Construct a ZipInputStream from the InputStream.
  • Iterate each ZipEntry, looking for matches to the desired path.

..will I still be able to test my Applet when it's not inside that jar? Or will I have to program two ways to get my Images?

The ZipInputStream will not work with loose resources in directories on the file system. But then, I would strongly recommend using a build tool such as Ant to build (compile/jar/sign etc.) the applet. It might take an hour or so to write the build script & check it, but thereafter you can build the project by a few keystrokes and a couple of seconds.

It would be quite annoying if I always have to extract and sign my jar if I want to test my Aplet

I'm not sure what you mean there. Where does the 'extract' come into it? In case I was not clear, a sand-boxed applet can load resources this way, from any Jar that is mentioned in the archive attribute. Another thing you might do, is to separate the resource Jar(s) from the applet Jar. Resources typically change less than code, so your build might be able to take some shortcuts.

I think I really have to consider putting my Images into a seperate directory outside the jar.

If you mean on the server, there will be no practical way to get a listing of the image files short of help from the server. E.G. Some servers are insecurely set up to produce an HTML based 'file list' for any directory with no default file (such as an index.html).


I have only got one jar, in which my classes, images and sounds are.

OK - consider moving the sounds & images into a separate Jar. Or at the very least, put them in the Jar with 'no compression'. While Zip comression techniques work well with classes, they are less efficient at compressing (otherwise already compressed) media formats.

I have to sign it because I use the "Preferences" class to save user settings."

There are alternatives to the Preferences for applets, such as cookies. In the case of plug-in 2 architecture applet, you can launch the applet (still embedded in the browser) using Java Web Start. JWS offers the PersistenceService. Here is my small demo. of the PersistenceService.

Speaking of JWS, that brings me to: Are you absolutely certain this game would be better as an applet, rather than an app (e.g. using a JFrame) launched using JWS?

Applets will give you no end of stress, and JWS has offered the PersistenceService since it was introduced in Java 1.2.

like image 23
Andrew Thompson Avatar answered Sep 28 '22 08:09

Andrew Thompson