Reputation: 1885
I have a path that points to a file on disk, say: C:\folder\dir\dir2\file.txt
. In the code, if an exception is thrown when working with this file, it will output the whole path. Ideally, it would be nice not to have the whole directory print out, rather something like ../../dir2/file.txt
.
It seems like I should be able to that with the java.nio.file relativize
method, I'm just not sure how.
Path file; // C:\folder\dir\di2\file.txt
file.relativize(file.getParent());
I'm approaching this the wrong way I'm sure, just not positive how to accomplish what I'd like.
Upvotes: 9
Views: 4991
Reputation: 279880
Get the current working directory
Path pwd = Paths.get("").toAbsolutePath();
and then relativize
the target Path
Path relative = pwd.relativize(target);
Upvotes: 12