【问题标题】:Get name of running Jar or Exe获取正在运行的 Jar 或 Exe 的名称
【发布时间】:2018-11-23 14:41:50
【问题描述】:

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

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

【问题讨论】:

    标签: java jar


    【解决方案1】:

    希望这对您有所帮助,我测试了代码并返回完整路径和名称。

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

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

    这是在 stackoverflow 上的一个类似但不是 == 问题上找到的 How to get the path of a running JAR file?

    【讨论】:

    • “给我一些反馈。” 小程序和任何使用 JWS 启动的东西都会失败。实施一个好主意通常是一个糟糕的策略。在 OP 提到这个想法之前,我们一直在猜测最好的帮助方式。
    • 您好我设法使用这种方法来获取路径,但它在 .target/classes 文件夹中,但我想读取目标文件夹下另一个文件夹中的清单文件,我是 Java 新手,有没有办法做到这一点?非常感谢。
    【解决方案2】:

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

    在编译后的应用程序中返回简单路径并在 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('!')));
    }
    

    【讨论】:

    • 我整个晚上都在努力寻找可行的方法。这救了我!!谢谢!我不知道为什么,但class.getProtectionDomain().getCodeSource().getLocation(), 和其他一切都返回了rsrc:.
    【解决方案3】:
      File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().toURI().g‌​etPath());  
    

    应该把罐子给你。

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

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

    【讨论】:

    • 加入我们post 2004并使用ProcessBuilder创建Process
    【解决方案4】:

    试试下面的

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

    【讨论】:

    • 欢迎来到 StackOverflow!请避免仅使用代码/命令的答案,并简要说明您的答案如何以及为何适用。 How do I write a good answer?
    • 不清楚它的作用,这段代码与上面的问题
    【解决方案5】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-24
      • 1970-01-01
      • 2014-07-27
      • 2022-08-23
      相关资源
      最近更新 更多