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?
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:
URLpointing to the Jar.InputStreamfrom theURL.ZipInputStreamfrom theInputStream.ZipEntry, looking for matches to the desired path.The
ZipInputStreamwill 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.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
archiveattribute. 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.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).
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.
There are alternatives to the
Preferencesfor 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
PersistenceServicesince it was introduced in Java 1.2.