简体   繁体   English

Java:如何使用nio Path规范化路径?

[英]Java: how to normalize paths with nio Path?

One of the really nice things about java.io.File is that it can normalize paths to a predictable format . 关于java.io.File一个非常好的事情是它可以将路径规范化可预测的格式

new File("/", inputPath).getPath() always returns a string with relative paths normalized out, and always starting and ending with predictable path separators. new File("/", inputPath).getPath()始终返回一个字符串,其相对路径已标准化,并始终以可预测的路径分隔符开头和结尾。

Is there a way to do this with the new nio Path or Paths classes? 有没有办法用新的nio PathPaths类做到这一点?

(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"

This code works: 此代码有效:

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);
        }
    }
}

Output: 输出:

/foo -> /foo
//foo -> /foo
foo/ -> /foo
foo/bar -> /foo/bar
foo/bar/../baz -> /foo/baz
foo//bar -> /foo/bar

NOTE however that this is NOT portable. 但请注意,这不是便携式的。 It won't work on Windows machines... 它不适用于Windows机器......

If you want a portable solution you can use memoryfilesystem , open a Unix filesystem and use that: 如果你想要一个可移植的解决方案,你可以使用memoryfilesystem ,打开一个Unix文件系统并使用它:

try (
    final FileSystem fs = MemoryFileSystem.newLinux().build();
) {
    // path operations here
}

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

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