相对于另一个切断URI

时间:2016-02-05 02:19:19

标签: java uri

我们resolvea/b + c/d转换为a/b/c/d

我们relativizea/b + a/b/c/d转换为c/d

有没有办法将a/b/c/d + c/d转换为a/b

对于我的特殊问题(类路径),URI不能转换为java.nio.file.Path s,错误

java.nio.file.InvalidPathException: Illegal char <:> at index 3: jar:file:/D:/devel/somejar.jar!/foo/Bar.class

我想解析一个条目的目录(例如,给定Bar.class)和URIgetClassLoader().getResource().toURI()产生的jar:file:/D:/devel/somejar.jar!/foo

3 个答案:

答案 0 :(得分:1)

您可以使用java.nio.file.Path,但您必须使用自定义文件系统,因为此处的URI方案为jar而不是fileThis page显示了一个示例。

URI uri = URI.create("jar:file:/D:/devel/somejar.jar!/foo/Bar.class");

String[] array = uri.toString().split("!");
String jarFile = array[0];
String entryPath = array[1];
try(FileSystem fs = FileSystems.newFileSystem(URI.create(jarFile), new HashMap<>())) {
    Path path = fs.getPath(entryPath);
    URI parentUri = path.getParent().toUri();
    ...
}

使用子字符串的简单方法:

URI uri = URI.create("jar:file:/D:/devel/somejar.jar!/foo/Bar.class");
URI parent = URI.create(uri.toString().substring(0, uri.toString().lastIndexOf("/")));

答案 1 :(得分:1)

// Call the plugin
document.getElementById('upload-post-images').onchange = function (e) {
    for(i = 0; i<=e.target.files.length; i++) {
       loadImage(
          e.target.files[i],
          function (img) {
              document.body.appendChild(img);
          },
          {maxWidth: 200} // Options
       );
    }
};

jar:file:/Library/Java/JavaVirtualMachines/jdk1.8.0_31.jdk/Contents/Home/jre/lib/rt.jar!/java/net/URISyntaxException.class jar:file:/Library/Java/JavaVirtualMachines/jdk1.8.0_31.jdk/Contents/Home/jre/lib/rt.jar!/java/net

toString is the trick

答案 2 :(得分:0)

我不确定你想要达到的目标。您可以使用正则表达式删除路径的末尾部分。我以String.class为例。

public static void main(final String[] args) throws Exception {
    // get URI of class
    String clazz = "String.class";

    URI resourceURI = String.class.getResource(clazz).toURI();
    System.out.println(resourceURI);
    System.out.println(resourceURI.toString().replaceAll("^(.+?)!?/?" + clazz + "$", "$1"));

    clazz = "/lang/String.class";
    System.out.println(resourceURI.toString().replaceAll("^(.+?)!?/?" + clazz + "$", "$1"));

    clazz = "java/lang/String.class";
    System.out.println(resourceURI.toString().replaceAll("^(.+?)!?/?" + clazz +  "$", "$1"));
}

如果您想尝试将数据加载到路径中,则可以执行以下操作:

public static void main(final String[] args) throws Exception {
    // get URI of class
    String clazz = "String.class";

    URI resourceURI = String.class.getResource(clazz).toURI();
    System.out.println(resourceURI.getScheme());
    System.out.println(resourceURI.getRawSchemeSpecificPart());
    URI fileURI = new URI(resourceURI.getRawSchemeSpecificPart());
    System.out.println(fileURI.getScheme());
    System.out.println(fileURI.getRawSchemeSpecificPart());
    Path path = Paths.get(fileURI);
    System.out.println(path);
    System.out.println(path.getParent());
}