简体   繁体   中英

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 .

new File("/", inputPath).getPath() always returns a string with relative paths normalized out, and always starting and ending with predictable path separators.

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"

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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