Java Nio相对路径的绝对路径 [英] Java Nio absolute path to relative path

查看:288
本文介绍了Java Nio相对路径的绝对路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个指向磁盘上文件的路径,例如: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.

似乎我应该能够使用

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相对路径的绝对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆