简体   繁体   English

如何从 java.nio.Path 获取路径字符串?

[英]How to get the path string from a java.nio.Path?

Rewrote question with more info用更多信息重写问题

I have some code that creates a Path object using relative paths, like this: Paths.get("..", "folder").resolve("filename") .我有一些使用相对路径创建Path对象的代码,如下所示: Paths.get("..", "folder").resolve("filename") Later, I want to get the path string "..\\folder\\filename" from it (I'm on windows, so backslashes).后来,我想从中获取路径字符串“..\\folder\\filename”(我在 Windows 上,所以反斜杠)。 When I run this code using manual compile or from Eclipse, this works fine.当我使用手动编译或从 Eclipse 运行此代码时,这工作正常。

However, when I run it using Maven, it doesn't work any more.但是,当我使用 Maven 运行它时,它不再起作用。 The toString() method returns [.., folder, filename] instead of an actual path string. toString()方法返回[.., folder, filename]而不是实际的路径字符串。 Using path.normalize() doesn't help.使用path.normalize()没有帮助。 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.使用path.toFile().getPath()确实返回了我正在寻找的内容,但我觉得应该有一个只使用nio.path API 的解决方案。

Use:采用:

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

Another solution woul be:另一个解决方案是:

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

However, you get strange results: Paths.get("/tmp", "foo").toString() returns /tmp/foo here.但是,您会得到奇怪的结果: Paths.get("/tmp", "foo").toString()在这里返回/tmp/foo What is your filesystem?你的文件系统是什么?

To complete the the fge's answer , I would add some info:为了完成fge 的回答,我会添加一些信息:

  1. normalize() simply removes redundant pieces of strings in your path, like . normalize()只是删除路径中多余的字符串片段,例如. or .. ;.. ; it does not operate at the OS level or gives you an absolute path from a relative path不在操作系统级别运行或为您提供相对路径的绝对路径
  2. toAbsolutePath() on the contrary gives you what the name says, the absolute path of the Path object. toAbsolutePath()相反,它为您提供了名称所说的Path对象的绝对路径。 But...但...
  3. toRealPath() resolves also soft and hard links (yes they exists also on Windows, so win user, you're not immune). toRealPath()也解析软链接和硬链接(是的,它们也存在于 Windows 上,所以赢得用户,你不能幸免)。 So it gives to you, as the name says, the real path.因此,正如名称所说,它为您提供了真正的路径。

So what's the best?那么什么是最好的呢? It depends, but IMHO I'll use toRealPath() the 99% of the cases.这取决于,但恕我直言,我将在 99% 的情况下使用toRealPath()

Source: Official javadoc来源: 官方 javadoc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM