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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With