【问题标题】:Java Convert Jar URL to FileJava 将 Jar URL 转换为文件
【发布时间】:2015-11-15 18:23:12
【问题描述】:

我正在尝试实现以下目标:从给定的Class 对象中,我希望能够检索它所在的文件夹或文件。这也应该适用于像java.lang.String 这样的系统类(它将返回rt.jar 的位置)。对于“源”类,该方法应返回根文件夹:

- bin
  - com
    - test
      - Test.class

将为file(com.test.Test.class) 返回bin 文件夹的位置。这是我目前的实现:

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 以及在编译器中使用它们的语言库。

【问题讨论】:

    标签: java file url jar uri


    【解决方案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);
    }
    

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2012-04-05
      • 1970-01-01
      • 2018-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多