2015-08-21 112 views
1

我試圖實現以下目標:從給定的Class對象中,我希望能夠檢索它所在的文件夾或文件。這也適用於像java.lang.String這樣的系統類(它將返回rt.jar的位置)。爲「源」類,該方法應返回的根文件夾:Java將Jar URL轉換爲文件

- bin 
    - com 
    - test 
     - Test.class 

將返回bin文件夾的位置爲file(com.test.Test.class)。這是迄今爲止我的執行:

public static File getFileLocation(Class<?> klass) 
{ 
    String classLocation = '/' + klass.getName().replace('.', '/') + ".class"; 
    URL url = klass.getResource(classLocation); 
    String path = url.getPath(); 
    int index = path.lastIndexOf(classLocation); 
    if (index < 0) 
    { 
     return null; 
    } 

    // Jar Handling 
    if (path.charAt(index - 1) == '!') 
    { 
     index--; 
    } 
    else 
    { 
     index++; 
    } 

    int index1 = path.lastIndexOf(':', index); 
    String newPath = path.substring(index1 + 1, index); 

    System.out.println(url.toExternalForm()); 
    URI uri = URI.create(newPath).normalize(); 

    return new File(uri); 
} 

然而,由於File(URI)構造函數拋出IllegalArgumentException此代碼失敗 - 「URI也不是絕對的。」我已經嘗試過使用newPath構建文件,但這個失敗的目錄結構與空間,像這樣的:

- Eclipse Workspace 
    - MyProgram 
    - bin 
     - Test.class 

這是由於該URL表示使用%20表示一個空格,其實這不被文件構造函數識別。

是否有一種有效且可靠的方法來獲取Java類的(類路徑)位置,該類對目錄結構和Jar文件都有效?

請注意,我不需要確切的類的確切文件 - 只有容器!我使用這段代碼來找到rt.jar以及在編譯器中使用它們的語言庫。

回答

1

你的代碼的輕微修改應該在這裏工作。你可以嘗試下面的代碼:

public static File getFileLocation(Class<?> klass) 
{ 
    String classLocation = '/' + klass.getName().replace('.', '/') + ".class"; 
    URL url = klass.getResource(classLocation); 
    String path = url.getPath(); 
    int index = path.lastIndexOf(classLocation); 
    if (index < 0) 
    { 
     return null; 
    } 

    String fileCol = "file:"; 
    //add "file:" for local files 
    if (path.indexOf(fileCol) == -1) 
    { 
     path = fileCol + path; 
     index+=fileCol.length(); 
    } 

    // Jar Handling 
    if (path.charAt(index - 1) == '!') 
    { 
     index--; 
    } 
    else 
    { 
     index++; 
    } 

    String newPath = path.substring(0, index); 

    System.out.println(url.toExternalForm()); 
    URI uri = URI.create(newPath).normalize(); 

    return new File(uri); 
} 

希望這會有所幫助。