Get name of running Jar or Exe

前端 未结 5 2109
长发绾君心
长发绾君心 2020-12-03 15:47

What I need to do is get the name of the running jar/exe file (it would be an EXE on windows, jar on mac/linux). I have been searching around and I can\'t seem to find out h

相关标签:
5条回答
  • 2020-12-03 16:12

    Try the following

    System.getProperty("java.class.path")
    
    0 讨论(0)
  • 2020-12-03 16:14

    Hope this can help you, I test the code and this return you the full path and the name.

    Maybe you want to play a little more with the code and give me some feed back.

    File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().toURI());‌
    

    This was found on a similar but not == question on stackoverflow How to get the path of a running JAR file?

    0 讨论(0)
  • 2020-12-03 16:20

    Using Lunch4j you can add an image name for exe file by editing generated xml, you have to change tag value true from false to true

    0 讨论(0)
  • 2020-12-03 16:27
      File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().toURI().g‌​etPath());  
    

    Should give you the jar.

    as for the exe, as I'm assuming you're using some sort of wrapper, you'll need to know the name of the exe before it's run. Then you could use something like :

       Process p = Runtime.getRuntime().exec
        (System.getenv("windir") +"\\system32\\"+"tasklist.exe");
    
    0 讨论(0)
  • 2020-12-03 16:31

    File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().toURI());‌

    returns simple path in the compiled application and an error in jar:

    URI is not hierarchical

    My solution is:

    private File getJarFile() throws FileNotFoundException {
        String path = Main.class.getResource(Main.class.getSimpleName() + ".class").getFile();
        if(path.startsWith("/")) {
            throw new FileNotFoundException("This is not a jar file: \n" + path);
        }
        path = ClassLoader.getSystemClassLoader().getResource(path).getFile();
    
        return new File(path.substring(0, path.lastIndexOf('!')));
    }
    
    0 讨论(0)
提交回复
热议问题