Java: how to normalize paths with nio Path?

前端 未结 1 672
小鲜肉
小鲜肉 2020-12-19 04:19

One of the really nice things about java.io.File is that it can normalize paths to a predictable format.

new Fil

相关标签:
1条回答
  • 2020-12-19 04:40

    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...

    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
    }
    
    0 讨论(0)
提交回复
热议问题