Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Nio absolute path to relative path

Tags:

java

nio

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.

like image 882
joshft91 Avatar asked Sep 24 '14 19:09

joshft91


1 Answers

Get the current working directory

Path pwd = Paths.get("").toAbsolutePath();

and then relativize the target Path

Path relative = pwd.relativize(target);
like image 173
Sotirios Delimanolis Avatar answered Nov 18 '22 09:11

Sotirios Delimanolis