Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

URI is not absolute?

Tags:

java

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?

like image 602
Grim Avatar asked Mar 04 '17 03:03

Grim


1 Answers

relativize returns a URI.

a new File(URI uri) takes...

uri - An absolute, hierarchical URI

You can instead try using the String constructor.

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.Path API instead of 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
like image 158
OneCricketeer Avatar answered Sep 20 '22 00:09

OneCricketeer