如何从java.nio.Path获取路径字符串? [英] How to get the path string from a java.nio.Path?

查看:435
本文介绍了如何从java.nio.Path获取路径字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用更多信息重写了问题

我有一些代码使用相对路径创建 Path 对象,例如这个: Paths.get(..,folder)。resolve(filename)。后来,我想从它获取路径字符串..\folder\filename(我在Windows上,所以反斜杠)。当我使用手动编译或从Eclipse运行此代码时,这可以正常工作。

I have some code that creates a Path object using relative paths, like this: Paths.get("..", "folder").resolve("filename"). Later, I want to get the path string "..\folder\filename" from it (I'm on windows, so backslashes). When I run this code using manual compile or from Eclipse, this works fine.

但是,当我使用Maven运行它时,它不再起作用。 toString()方法返回 [..,文件夹,文件名] 而不是实际的路径字符串。使用 path.normalize()没有帮助。使用 path.toFile()。getPath()会返回我正在寻找的内容,但我觉得应该只使用 nio的解决方案.path API。

However, when I run it using Maven, it doesn't work any more. The toString() method returns [.., folder, filename] instead of an actual path string. Using path.normalize() doesn't help. Using path.toFile().getPath() does return what I'm looking for, but I feel there should be a solution using just the nio.path API.

推荐答案

使用:

Paths.get(...).normalize().toString()

另一个解决方案是:

Paths.get(...).toAbsolutePath().toString()

然而,你会得到奇怪的结果: Paths.get(/ tmp,foo)。toString()在这里返回 / tmp / foo 。你的文件系统是什么?

However, you get strange results: Paths.get("/tmp", "foo").toString() returns /tmp/foo here. What is your filesystem?

这篇关于如何从java.nio.Path获取路径字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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