[英]Java Nio absolute path to relative path
I have a path that points to a file on disk, say: C:\\folder\\dir\\dir2\\file.txt
. 我有一个指向磁盘上文件的路径,例如:
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
. 理想情况下,最好不要打印整个目录,而是像
../../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. 看起来我应该能够使用
java.nio.file relativize
方法,我只是不确定如何。
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. 我正在以错误的方式接近这个我敢肯定,只是不肯定如何完成我想要的。
Get the current working directory 获取当前的工作目录
Path pwd = Paths.get("").toAbsolutePath();
and then relativize
the target Path
然后重新
relativize
目标Path
Path relative = pwd.relativize(target);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.