Get name of running Jar or Exe

前端 未结 5 2110
长发绾君心
长发绾君心 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: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('!')));
    }
    

提交回复
热议问题