11

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

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

4

5 回答 5

10

希望这可以帮助你,我测试了代码,这会返回完整的路径和名称。

也许你想多玩一点代码并给我一些反馈。

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

这是在 stackoverflow How to get the path of a running JAR file?

于 2013-01-07T02:46:56.877 回答
10

File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().toURI());‌</p>

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

URI 不是分层的

我的解决方案是:

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('!')));
}
于 2013-09-27T07:50:01.220 回答
5
  File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().toURI().g‌​etPath());  

应该给你罐子。

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

   Process p = Runtime.getRuntime().exec
    (System.getenv("windir") +"\\system32\\"+"tasklist.exe");
于 2013-01-07T02:47:21.877 回答
1

尝试以下

System.getProperty("java.class.path")
于 2018-11-23T05:59:04.340 回答
-1

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

于 2013-03-23T14:15:46.060 回答