2013-01-07 36 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('!'))); 
}