java 获取正在运行的 Jar 或 Exe 的名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14189162/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 15:24:41  来源:igfitidea点击:

Get name of running Jar or Exe

javajar

提问by user1947236

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 how.

我需要做的是获取正在运行的 jar/exe 文件的名称(它在 windows 上是一个 EXE,在 mac/linux 上是 jar)。我一直在四处寻找,但似乎无法找到方法。

How to get name of running Jar or Exe?

如何获取正在运行的 Jar 或 Exe 的名称?

采纳答案by Christopher Cabezudo Rodriguez

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?

这是在 stackoverflow如何获取正在运行的 JAR 文件的路径上的一个类似但不是 == 的问题中发现的

回答by Alexander

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

文件(MyClass.class.getProtectionDomain().getCodeSource().getLocation().toURI());?

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

在已编译的应用程序中返回简单路径并在 jar 中返回错误:

URI is not hierarchical

URI 不是分层的

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('!')));
}

回答by Mark

  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 :

至于 exe,因为我假设您正在使用某种包装器,所以您需要在运行之前知道 exe 的名称。然后你可以使用类似的东西:

   Process p = Runtime.getRuntime().exec
    (System.getenv("windir") +"\system32\"+"tasklist.exe");

回答by Saikat Debnath

Try the following

尝试以下

System.getProperty("java.class.path")

回答by Twinscode

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

使用Lunch4j,您可以通过编辑生成的 xml 为 exe 文件添加图像名称,您必须将标签值 true 从 false 更改为 true