Real'sHowTo AddThis Feed Button
Custom Search

Determine if running from JARTag(s): Environment


package com.rgagnon;

public class HelloClass {
 public static void main(String[] args) {
    new HelloClass().say();
 }

 public void say() {
   String className = this.getClass().getName().replace('.', '/');
   String classJar =
     this.getClass().getResource("/" + className + ".class").toString();
   if (classJar.startsWith("jar:")) {
     System.out.println("*** running from jar!");
   }
   System.out.println(classJar);
 }
}
The output
>jar cvfm Hello.jar manifest.mft com\rgagnon\HelloClass.class
added manifest
adding: com/rgagnon/HelloClass.class (in=1059) (out=601) (deflated 43%)

>java com.rgagnon.HelloClass
file:/C:/DEV/WORK/JAVA/com/rgagnon/HelloClass.class

>java -jar Hello.jar
*** running from jar!
jar:file:/C:/DEV/WORK/JAVA/Hello.jar!/com/rgagnon/HelloClass.class
Here a variation on this subject, a method to return the name of the current running jar.
package com.rgagnon.howto;

public class RunningJar {
 public static void main(String[] args) {
   String runningJarName = new RunningJar().getRunningJarName();
   if (runningJarName != null) {
     System.out.println("Running from " + runningJarName);
   }
   else {
     System.out.println("Not running from a jar");
   }
 }

 public String getRunningJarName() {
   String className = this.getClass().getName().replace('.', '/');
   String classJar =
     this.getClass().getResource("/" + className + ".class").toString();
   if (classJar.startsWith("jar:")) {
     String vals[] = classJar.split("/");
     for (String val: vals) {
       if (val.contains("!")) {
         return val.substring(0, val.length() - 1);
       }
     }
   }
   return null;
 }
}

/*
output :

>java -jar yop.jar
Running from yop.jar

>ren yop.jar yip.jar

>java -jar yip.jar
Running from yip.jar

*/

See these related HowTo's : Obtain from where a Class is loaded  Get the "root" of an application


blog comments powered by Disqus


If you find this article useful, consider making a small donation
to show your support for this Web site and its content.

Written and compiled by Réal Gagnon ©1998-2014
[ home ]