Java URI 不是绝对的吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42591750/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 00:15:44  来源:igfitidea点击:

URI is not absolute?

java

提问by Grim

I have a File

我有一个文件

/user/guest/work/test/src/main/java/Test.java

And a File-Object:

和一个文件对象:

File f = new File("/user/guest/work/test/src/main/java/Test.java");

I need this outputs

我需要这个输出

System.out.println(f);                   ->                       src/main/java/Test.java
System.out.println(f.getAbsolutePath()); -> /user/guest/work/test/src/main/java/Test.java

I tried:

我试过:

File relativeTo = new File("/user/guest/work/test");
new File(relativeTo.toURI().relativize(f.toURI()));

but it is throwing a

但它正在抛出一个

java.lang.IllegalArgumentException: URI is not absolute
   at java.io.File.<init>(File.java:416)
   at Test.<init>(Test.java:43)

How to get the required output?

如何获得所需的输出?

采纳答案by OneCricketeer

relativizereturns a URI.

relativize返回一个 URI。

a new File(URI uri)takes...

一个new File(URI uri)需要...

uri - An absolute, hierarchical URI

uri -绝对的分层 URI

You can instead try using the String constructor.

您可以改为尝试使用 String 构造函数。

new File(relativeTo.toURI().relativize(f.toURI()).toString());


You have access to that file other ways, however

但是,您可以通过其他方式访问该文件

For example, you can try going through the java.nio.file.PathAPI instead of java.io.File

例如,您可以尝试通过java.nio.file.PathAPI 而不是java.io.File

Like

喜欢

Path path = Paths.get("/", "user", "guest", "workspace", 
    "test", "src", "main", "java", "Test.java");
Path other = ...
Path relPath = other.relativize(path);

//    relPath.toString(); // print it
//    relPath.toFile();   // get a file

回答by Pulkit

You can use path resolve to relativize file paths

您可以使用路径解析来相对化文件路径

  File f = new File("/user/guest/workspace/test/src/main/java/Test.java");
  File relativeTo = new File("/user/guest/workspace/test");
  System.out.println(new File(relativeTo.toPath().resolve(f.toPath()).toUri()));