devxlogo

Load Images off JAR Files

Load Images off JAR Files

Packing resources (classes, sound files, images) in a JAR file is good way of reducing download time and decreasing distribution size. This tip shows you how to load images off a JAR file.Say you have a JAR file containing some GIF images that your application will use. The following class provides some means of extraction from a JAR file:

 public class JarExtractor { private Hashtable m_sizes=new Hashtable(); private Hashtable m_jarContents=new Hashtable(); private String m_jarFileName; public JarExtractor(String jarFileName) { this.m_jarFileName=jarFileName; initialize(); } public byte[] getImageData(String name) { return (byte[])m_jarContents.get(name); } private void initialize() { ZipFile zf=null; try { // let's get the sizes. zf=new ZipFile(m_jarFileName); Enumeration e=zf.entries(); while (e.hasMoreElements()) { ZipEntry ze=(ZipEntry)e.nextElement(); m_sizes.put(ze.getName(),new Integer((int)ze.getSize())); } zf.close(); zf=null; // put resources into m_jarContents FileInputStream fis=new FileInputStream(m_jarFileName); BufferedInputStream bis=new BufferedInputStream(fis); ZipInputStream zis=new ZipInputStream(bis); ZipEntry ze=null; while ((ze=zis.getNextEntry())!=null) { if (ze.isDirectory()) { continue; } int size=(int)ze.getSize(); if (size==-1) { size=((Integer)m_sizes.get(ze.getName())).intValue(); } byte[] b=new byte[(int)size]; int rb=0; int chunk=0; while (((int)size - rb) > 0) { chunk=zis.read(b,rb,(int)size - rb); if (chunk==-1) { break; } rb+=chunk; } zis.close(); m_jarContents.put(ze.getName(),b); } } catch (NullPointerException e){/*handle exception*/} catch (FileNotFoundException e){/*handle exception*/} catch (IOException e){/*handle exception*/} } 

Now, say, we have a JAR file “images.jar” that contains an image file named “myImage.gif”. To get that image we can do:

 JarExtractor je = new JarExtractor ("Images.jar"); Image anImage = Toolkit.getDefaultToolkit().createImage (je.getImageData ("myImage.gif"); 

This uses getImageData of JarExtractor to extract the raw byte data of the image we want. The same principle can be applied to loading of sound files, class files, etc. from a JAR file.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist