Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can my JAR open itself as a stream?

Tags:

java

I'm trying to open a JAR as a stream, but can't understand where to get this stream...

JarInputStream s = new JarInputStream(/* what is here? */);

Where to get this stream? I'm trying to open the JAR which is currently is in charge.

like image 536
yegor256 Avatar asked Dec 05 '25 07:12

yegor256


2 Answers

From my answer to a similar question:

CodeSource src = MyClass.class.getProtectionDomain().getCodeSource();
if (src != null) {
  URL jar = src.getLocation();
  ZipInputStream zip = new ZipInputStream(jar.openStream());
  /* Now examine the ZIP file entries to find those you care about. */
  ...
} 
else {
  /* Fail... */
}
like image 166
erickson Avatar answered Dec 07 '25 19:12

erickson


Look up a class that is in the JAR. Eg:

Class clazz = SomeClass.class;
URL resource = clazz.getResource(clazz.getSimpleName()+".class");
JarFile jarFile = ((JarURLConnection)resource.openConnection()).getJarFile();

I know you wanted a JarInputStream but I would bet JarFile does what you want.

like image 29
Plaudit Design Avatar answered Dec 07 '25 19:12

Plaudit Design