Getting the directory inside .jar

I am trying to access the directory inside my jar file. I want to view all the files inside the directory itself. I tried, for example, to use 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 as soon as I put the contents in the jar, this happens for 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 does not work inside the jar, because I get a URI not hierarchical error. I am sure that the catalog exists inside the jar. How can I get the contents of Images inside a jar?

+7
source share
8 answers

Paths inside Jars are paths, not actual directories, as you can use them on the file system. To get all resources in a specific Jar file path:

  • Type the URL pointing to the Jar.
  • Get InputStream from URL .
  • Build a ZipInputStream from InputStream .
  • Iterate ZipEntry each ZipEntry , looking for matches with the desired path.

.. can I still check my applet when it is not inside this jar? Or will I have to program two ways to get my images?

ZipInputStream will not work with free resources in file system directories. But then I highly recommend using a build tool such as Ant to build (compile / gang / character, etc.) the applet. It may take an hour or so to write the script assembly and test it, but after that you can create the project with a few keystrokes and a few seconds.

It would be very unpleasant if I always had to extract and sign my jar, if I want to check my Aplet

I'm not sure what you mean. Where does the “extract" come from? In case I was not clear, the sandbox applet can load resources this way from any Jar that is mentioned in the archive attribute. Another thing you can do is separate the Jar (s) resources from the Jar applet. Resources usually change less than code, so your assembly may have several shortcuts.

I think I really need to consider placing my images in a separate directory outside the bank.

If you mean on the server, there will be no practical way to get a listing of image files without the help of the server. EG. Some servers are unstable for creating an “HTML-based file list” for any directory without a default file (for example, index.html).


I have only one bank in which my classes, images and sounds.

OK - consider moving sounds and images to a separate jar. Or at least put them in a jar without compression. While Zip's collection methods work well with classes, they are less efficient at compressing (otherwise already compressed) media formats.

I need to sign it because I use the Preferences class to save user preferences. "

There are alternatives to Preferences for applets, such as cookies. In the case of an applet with plugin 2, you can launch the applet (still built into the browser) using Java Web Start . JWS offers a PersistenceService. Here is my little demonstration . PersistenceService services .

Speaking of JWS, this brings me to: are you absolutely sure that this game will be better than an applet and not an application (for example, using JFrame ) launched using JWS?

Applets will not give you any stress, and JWS has offered PersistenceService since its introduction in Java 1.2.

+5
source

Here is a solution that should work, considering that you are using Java 7 ... The "trick" is to use the new API files. Oracle JDK provides a FileSystem implementation that can be used to view / modify ZIP files, including banks.

Preliminary: grab System.getProperty("java.class.path", ".") , System.getProperty("java.class.path", ".") this will give you all the entries in a specific class path.

First, define a method to get the FileSystem out from the pathpath 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 determine if the path exists in the file system:

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

Use it to search your directory.

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

And don't forget .close() a FileSystem as soon as you are done with it!

Here is a main() example demonstrating how to read all root jar entries:

 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); } 
+3
source

You can use the PathMatchingResourcePatternResolver provided by Spring.

 public class SpringResourceLoader { public static void main(String[] args) throws IOException { PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); // Ant-style path matching Resource[] resources = resolver.getResources("/Images/**"); for (Resource resource : resources) { System.out.println("resource = " + resource); InputStream is = resource.getInputStream(); BufferedImage img = ImageIO.read(is); System.out.println("img.getHeight() = " + img.getHeight()); System.out.println("img.getWidth() = " + img.getWidth()); } } } 

I did not like the returned Resource , but you got the image.

Add this to your maven dependency (when using maven):

 <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>3.1.2.RELEASE</version> </dependency> 

This will work directly from Eclipse / NetBeans / IntelliJ and in a deployed bank.

Running from IntelliJ gives me the following result:

 resource = file [C:\Users\maba\Development\stackoverflow\Q12016222\target\classes\pictures\BMW-R1100S-2004-03.jpg] img.getHeight() = 768 img.getWidth() = 1024 

Running from the command line with an executable bank gives me the following result:

 C:\Users\maba\Development\stackoverflow\Q12016222\target>java -jar Q12016222-1.0-SNAPSHOT.jar resource = class path resource [pictures/BMW-R1100S-2004-03.jpg] img.getHeight() = 768 img.getWidth() = 1024 
+1
source

I think you can directly access resources in a ZIP / JAR file. Please see the Tutorial, which provides a solution to your question.

How to extract Java resources from JAR and zip archives

Hopes that help

0
source

If I understand your problem, you want to check the directory inside the jar and check all the files inside this directory. You can do something like:

 JarInputStream jar = new JarInputStream(new FileInputStream("D:\\x.jar")); JarEntry jarEntry ; while(true) { jarEntry = jar.getNextJarEntry(); if(jarEntry != null) { if(jarEntry.isDirectory() == false) { String str = jarEntry.getName(); if(str.startsWith("weblogic/xml/saaj")) { anything which comes here are inside weblogic\xml\saaj directory } } } } 
0
source

What you are looking for here may be a JarEntry-list Jar ... I did some similar work during the gradient school ... Here you can get a modified class ( http://code.google.com/p/marcellodesales-cs -research / source / browse / trunk / grad-ste-ufpe-brazil / ptf-add-on-dev / src / br / ufpe / cin / stp / global / filemanager / JarFileContentsLoader.java ) Please note that the URL contains an older Java class not using Generics ...

This class returns a set of URLs with the jar: file: / protocol for a given token ...

 package com.collabnet.svnedge.discovery.client.browser.util; import java.io.IOException; import java.net.URL; import java.util.Enumeration; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import java.util.jar.JarEntry; import java.util.jar.JarFile; public class JarFileContentsLoader { private JarFile jarFile; public JarFileContentsLoader(String jarFilePath) throws IOException { this.jarFile = new JarFile(jarFilePath); } /** * @param existingPath an existing path string inside the jar. * @return the set of URL from inside the Jar (whose protocol is "jar:file:/" */ public Set<URL> getDirEntries(String existingPath) { Set<URL> set = new HashSet<URL>(); Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { String element = entries.nextElement().getName(); URL url = getClass().getClassLoader().getResource(element); if (url.toString().contains("jar:file") && !element.contains(".class") && element.contains(existingPath)) { set.add(url); } } return set; } public static void main(String[] args) throws IOException { JarFileContentsLoader jarFileContents = new JarFileContentsLoader( "/u1/svnedge-discovery/client-browser/lib/jmdns.jar"); Set<URL> entries = jarFileContents.getDirEntries("impl"); Iterator<URL> a = entries.iterator(); while (a.hasNext()) { URL element = a.next(); System.out.println(element); } } } 

The conclusion will be:

 jar:file:/u1/svnedge-discovery/client-browser/lib/jmdns.jar!/javax/jmdns/impl/constants/ jar:file:/u1/svnedge-discovery/client-browser/lib/jmdns.jar!/javax/jmdns/impl/tasks/state/ jar:file:/u1/svnedge-discovery/client-browser/lib/jmdns.jar!/javax/jmdns/impl/tasks/resolver/ jar:file:/u1/svnedge-discovery/client-browser/lib/jmdns.jar!/javax/jmdns/impl/ jar:file:/u1/svnedge-discovery/client-browser/lib/jmdns.jar!/javax/jmdns/impl/tasks/ 
0
source

Can the following code example help you

  Enumeration<URL> inputStream = BrowserFactory.class.getClassLoader().getResources("."); System.out.println("INPUT STREAM ==> "+inputStream); System.out.println(inputStream.hasMoreElements()); while (inputStream.hasMoreElements()) { URL url = (URL) inputStream.nextElement(); System.out.println(url.getFile()); } 
0
source

IF you really want to process JAR files, such as directories, please see TrueZIP 7 . Perhaps something like the following:

 URL url = ... // whatever URI uri = url.toURI(); TFile file = new TFile(uri); // File-look-alike in TrueZIP 7 if (file.isDirectory) // true for regular directories AND JARs if the module truezip-driver-file is on the class path for (TFile entry : file.listFiles()) // iterate top level directory System.out.println(entry.getPath()); // or whatever 

Regards, Christian

0
source

All Articles