问题描述
我有一个指向磁盘上文件的路径,例如:C:\folder\dir\dir2\file.txt
.在代码中,如果使用此文件时引发异常,它将输出整个路径.理想情况下,最好不要打印出整个目录,而是像../../dir2/file.txt
这样.
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
.
似乎我应该能够使用 java.nio.file relativize
方法,我不确定该怎么做.
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.
推荐答案
获取当前工作目录
Path pwd = Paths.get("").toAbsolutePath();
然后relativize
目标Path
Path relative = pwd.relativize(target);
这篇关于Java Nio相对路径的绝对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!