Java:如何使用nio Path规范化路径? [英] Java: how to normalize paths with nio Path?
问题描述
java.io.File
的真正好处之一是,它可以标准化路径为可预测的格式.
One of the really nice things about java.io.File
is that it can normalize paths to a predictable format.
new File("/", inputPath).getPath()
始终返回规范化了相对路径的字符串,并且始终以可预测的路径分隔符开始和结束.
new File("/", inputPath).getPath()
always returns a string with relative paths normalized out, and always starting and ending with predictable path separators.
有没有办法用新的nio Path
或Paths
类做到这一点?
Is there a way to do this with the new nio Path
or Paths
classes?
(还要注意,我正在处理其他系统的抽象路径,这与任何本地文件系统无关)
(Note also that I am dealing with abstract paths for other systems, this has nothing to do with any local filesystem)
我想要的其他行为示例:
Further examples of behavior I want:
- "/foo" -> "/foo"
- "//foo/" -> "/foo"
- "foo/" -> "/foo"
- "foo/bar" -> "/foo/bar"
- "foo/bar/../baz" -> "/foo/baz"
- "foo//bar" -> "/foo/bar"
推荐答案
此代码有效:
public final class Foo
{
private static final List<String> INPUTS = Arrays.asList(
"/foo", "//foo", "foo/", "foo/bar", "foo/bar/../baz", "foo//bar"
);
public static void main(final String... args)
{
Path path;
for (final String input: INPUTS) {
path = Paths.get("/", input).normalize();
System.out.printf("%s -> %s\n", input, path);
}
}
}
输出:
/foo -> /foo
//foo -> /foo
foo/ -> /foo
foo/bar -> /foo/bar
foo/bar/../baz -> /foo/baz
foo//bar -> /foo/bar
但是请注意,这是不可移植的.在Windows机器上将无法使用...
NOTE however that this is NOT portable. It won't work on Windows machines...
如果您想使用便携式解决方案,则可以使用内存文件系统,打开Unix文件系统并使用:
If you want a portable solution you can use memoryfilesystem, open a Unix filesystem and use that:
try (
final FileSystem fs = MemoryFileSystem.newLinux().build();
) {
// path operations here
}
这篇关于Java:如何使用nio Path规范化路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!