2014-01-16 20 views
-1

我想將URL轉換爲字符串。我在網上搜索,找不到任何有用的東西。顯然有一個toString(URL)方法,但我無法得到這個工作。如何將URL對象轉換爲字符串

public String getLocationJar(){ 
    URL fileLocation = getClass().getProtectionDomain().getCodeSource().getLocation(); 

    return toString(fileLocation); 
} 
+0

你什麼意思,你不能得到那個工作?你的期望是什麼,實際結果是什麼? –

+1

爲什麼我沒有工作?發佈你已經嘗試過的代碼,所以我們更容易幫助你。 – Christian

+0

對不起,補充。我也試過用URL.toString(fileLocation),但沒有。 – user3080274

回答

3

如果我理解正確的,你只需要或者調用fileLocation.toString()也許fileLocation.getPath()。下面的代碼:

URL fileLocation = Test.class.getProtectionDomain().getCodeSource().getLocation(); 

System.out.println(fileLocation.toString()); 
System.out.println(fileLocation.getPath()); 

輸出所需的路徑:

file:/C:/Users/xxx/Dev/Workspace/proj/target/classes/ 
/C:/Users/xxx/Dev/Workspace/proj/target/classes/ 

因此,只要改變你的代碼return fileLocation.toString()