2015-08-21 109 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); 
} 

希望这会有所帮助。