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