public final class JarResource
{
private String jarFileName;
private Map<String, Long> hashSizes = new HashMap<String, Long>();
private Map<String, Object> hashJarContents = new HashMap<String, Object>();
public JarResource(String jarFileName) throws Exception
{
this.jarFileName = jarFileName;
ZipFile zipFile = new ZipFile(this.jarFileName);
Enumeration<ZipEntry> e = (Enumeration<ZipEntry>) zipFile.entries();
while (e.hasMoreElements())
{
ZipEntry zipEntry = e.nextElement();
if(!zipEntry.isDirectory())
{
hashSizes.put(getSimpleName(zipEntry.getName()), zipEntry.getSize());
}
}
zipFile.close();
// extract resources and put them into the hashMap.
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;
}
else
{
long size = (int) ze.getSize();
// -1 means unknown size.
if (size == -1)
{
size = hashSizes.get(ze.getName());
}
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;
}
hashJarContents.put(ze.getName(), b);
}
}
zis.close();
}
public byte[] getResource(String name)
{
return (byte[]) hashJarContents.get(name);
}
private String getSimpleName(String entryName)
{
// Remove ".jar" extension
int index = entryName.indexOf("/");
String fileNameWithoutExt = entryName.substring(index, entryName.length());
return fileNameWithoutExt;
}
}
Then use this class to load your resource:
public static void main(String[] args) throws Exception
{
JarResource jr = new JarResource("/home/mjiang/Downloads/solr-4.8.0/dist/solr-cell-4.8.0-test.jar");
byte[] resource = jr.getResource("/META-INF/NOTICE.txt");
InputStream input = new ByteInputStream(resource, resource.length);
BufferedReader dis = new BufferedReader(new InputStreamReader(input));
String line = "";
while((line = dis.readLine()) != null)
{
System.out.println(line);
}
dis.close();
}