java 获取文件路径的相对路径?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14898224/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 17:45:58  来源:igfitidea点击:

Get relative path of a File path?

javafilepathrelative-pathjava-7

提问by stefan.at.wpf

I need to get the relative file path (relative to the program executable path) from a Fileobject.

我需要从File对象中获取相对文件路径(相对于程序可执行路径)。

What's the best way to do this? Fileoffers only methods for the absolute path. Maybe getting execution path manually and then cut this path off from the absolute path to get a relative path?

做到这一点的最佳方法是什么?File仅提供绝对路径的方法。也许手动获取执行路径,然后从绝对路径中切断这条路径以获得相对路径?

I am on Java 7, just in case java.nio has some helping method for that.

我在 Java 7 上,以防万一 java.nio 有一些帮助方法。

Tahnks for any hint!

感谢您的任何提示!

回答by Sean Landsman

As you're using Java 7 you can make use of the new Path class, which has a number of really cool methods, including Path.relativize.

当您使用 Java 7 时,您可以使用新的 Path 类,它有许多非常酷的方法,包括Path.relativize

回答by Carlo Pellegrini

You need the method:

你需要的方法:

Path relativize(Path other)

of java.nio.file.Path.

java.nio.file.Path

To obtain a Path from a file you could use its Path toPath()method.

要从文件中获取路径,您可以使用它的Path toPath()方法。