java – 相对于另一个切断URI

我们有决心将a / b c / d转换为a / b / c / d.

我们已经将a / b a / b / c / d转换为c / d的相对化.

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

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

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

我想解析一个条目的目录(例如给定的Bar.class)和由getClassLoader()生成的URI.getResource().toURI()到jar:file:/ D:/devel/somejar.jar!/ FOO.

最佳答案 您可以使用java.nio.file.Path但是您必须使用自定义文件系统,因为此处的URI方案是jar not file.
This 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("/")));
点赞