Can you tell on runtime if you're running java from within a jar?

后端 未结 8 1505
星月不相逢
星月不相逢 2020-12-09 14:54

I have an application that some of my users run from Eclipse, and others run it by using a jar file.

I want some actions to be done when running from within the jar,

相关标签:
8条回答
  • 2020-12-09 15:19

    From How-To

    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);
     }
    }
    

    Will give:

    >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
    

    As pointed out by Hosam Aly, this does not answer exactly the question.
    I leave it there for general reference, as a wiki answer.

    0 讨论(0)
  • 2020-12-09 15:30

    If you query the JAR file name it will work if running from a JAR file otherwise it will return something like classes so the following code can be used:

    import java.io.File;
    
    public class JarUtilities
    {
        public static String getJarName()
        {
            return new File(JarUtilities.class.getProtectionDomain()
                                    .getCodeSource()
                                    .getLocation()
                                    .getPath())
                           .getName();
        }
    
        public static boolean runningFromJar()
        {
            return getJarName().contains(".jar");
        }
    }
    

    EDIT:

    If you need more accuracy and to be resistant against renaming of the file extension, checking whether the file contains the MANIFEST.MF should work:

    public static boolean runningFromJAR()
    {
        try
        {
            String jarFilePath = new File(JarUtilities.class.getProtectionDomain()
                    .getCodeSource()
                    .getLocation()
                    .getPath()).
                    toString();
            jarFilePath = URLDecoder.decode(jarFilePath, "UTF-8");
    
            try (ZipFile zipFile = new ZipFile(jarFilePath))
            {
                ZipEntry zipEntry = zipFile.getEntry("META-INF/MANIFEST.MF");
    
                return zipEntry != null;
            }
        } catch (Exception exception)
        {
            return false;
        }
    }
    
    0 讨论(0)
提交回复
热议问题