Mega Code Archive

 
Categories / Java Tutorial / File
 

Load resource from Jar file

import java.io.BufferedInputStream; import java.io.FileInputStream; import java.util.Enumeration; import java.util.Hashtable; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.zip.ZipInputStream; public final class JarResources {   Hashtable htSizes = new Hashtable();   Hashtable htJarContents = new Hashtable();   private String jarFileName;   public JarResources(String jarFileName) throws Exception {     this.jarFileName = jarFileName;     ZipFile zf = new ZipFile(jarFileName);     Enumeration e = zf.entries();     while (e.hasMoreElements()) {       ZipEntry ze = (ZipEntry) e.nextElement();       htSizes.put(ze.getName(), new Integer((int) ze.getSize()));     }     zf.close();     // extract resources and put them into the hashtable.     FileInputStream fis = new FileInputStream(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();       // -1 means unknown size.       if (size == -1) {         size = ((Integer) htSizes.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;       }       htJarContents.put(ze.getName(), b);     }   }   public byte[] getResource(String name) {     return (byte[]) htJarContents.get(name);   }   private String dumpZipEntry(ZipEntry ze) {     StringBuffer sb = new StringBuffer();     if (ze.isDirectory()) {       sb.append("d ");     } else {       sb.append("f ");     }     if (ze.getMethod() == ZipEntry.STORED) {       sb.append("stored   ");     } else {       sb.append("defalted ");     }     sb.append(ze.getName());     sb.append("\t");     sb.append("" + ze.getSize());     if (ze.getMethod() == ZipEntry.DEFLATED) {       sb.append("/" + ze.getCompressedSize());     }     return (sb.toString());   }   public static void main(String[] args) throws Exception {     JarResources jr = new JarResources("a.jar");     byte[] buff = jr.getResource("b.gif");   } }