2013-01-07 31 views
3

我需要做的是获取正在运行的jar/exe文件的名称(这将是Windows上的EXE,Mac/Linux上的jar)。我一直在四处寻找,我似乎无法找出如何。获取运行Jar或Exe的名字

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

回答

5

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

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

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

这是一个类似但不==问题发现计算器 How to get the path of a running JAR file?

+0

* “给我一些反馈。” *失败的小程序,并使用JWS任何发射。实施一个好主意通常是一个糟糕的策略。在OP提到这个想法是什么之前,我们正在猜测最佳的帮助方式。 –

4
File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().toURI().g‌​etPath()); 

应该给你的罐子。

至于exe,因为我假设你正在使用某种包装,你需要知道exe的名称,然后才能运行。然后,你可以使用类似:

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

加入我们[post 2004](http://en.wikipedia.org/wiki/Java_version_history#J2SE_5.0_.28September_30.2C_2004.29)并使用'ProcessBuilder'来创建'Process'。 –

0

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

7

文件(MyClass的。.class.getProtectionDomain()getCodeSource()的getLocation()toURI());在所述编译的应用程序

返回简单的路径和在罐一个错误:

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