2011-06-06 100 views
0

我想從放置jar文件的目錄中獲取文本文件。從放置jar文件的特定目錄獲取文件

假設我的桌面應用程序'foo.jar'文件放置在d:\安裝的Windows中。 在'foo.jar'應用程序運行時,我想在同一個目錄下有一個test.txt文件。 如何在我的'foo.jar'應用程序中獲取特定路徑? 總之,我想獲取放置它的'foo.jar'文件的路徑。

回答

3

注意,實際的代碼不依賴於實際的類位置的包內,但在總體上可能看起來像:

URL root = package.Main.class.getProtectionDomain().getCodeSource().getLocation(); 
String path = (new File(root.toURI())).getParentFile().getPath(); 
... 
// handle file.txt in path 
+0

嘿它是格柵,但仍然無法讀取test.txt文件。有什麼想法嗎? – Nirav 2011-06-06 05:27:01

+0

@Nirav:嘗試呼應'路徑'到標準輸出,它會讓事情變得更容易理解;您可能還必須將'file.txt'放到您的'build'路徑中進行測試。 – 2011-06-06 05:29:45

+0

不,它不工作。 – Nirav 2011-06-06 05:38:36

1

大多數JAR文件使用的是記得從哪裏JAR有codesource的一個URLClassLoader的裝已加載。您可以使用這些知識來獲取JVM從JVM加載的目錄位置。您也可以使用ProtectionDomain類來獲取CodeSource(如其他答案中所示;誠然,這可能會更好)。

返回的位置通常爲file:協議類型,因此您必須移除此協議標識符以獲取實際位置。以下是執行此活動的簡短片段;您可能希望建立更多的錯誤檢查和邊緣檢測的情況下,如果你需要在生產中使用它:

public String getCodeSourceLocation() { 
     ClassLoader contextClassLoader = CurrentJARContext.class.getClassLoader(); 
     if(contextClassLoader instanceof URLClassLoader) 
     { 
      URLClassLoader classLoader = (URLClassLoader)contextClassLoader; 
      URL[] urls = classLoader.getURLs(); 
      String externalForm = urls[0].toExternalForm(); 
      externalForm = externalForm.replaceAll("file:\\/", ""); 
      externalForm = externalForm.replaceAll("\\/", "\\" + File.separator); 
      return externalForm; 
     } 
     return null; 
    } 
0

我發現我自己的問題的最簡單的回答。
String path = System.getProperty(「user.dir」);

+1

僅當您從同一目錄啓動java可執行文件時纔有效。 – 2011-06-06 07:36:12

+0

抱歉,我無法得到你能請你解釋一下例子。 – Nirav 2011-06-06 07:37:58

+0

如果您從'C:'''java_jar D:> aJAR.jar'啓動應用程序,user.dir將包含'C:''而不是'D:>'。 – 2011-06-06 07:41:24