Java: how to normalize paths using nio Path?

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

new File("/", inputPath).getPath() always returns a string with normalized relative paths and always starts and ends 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 file system)

Other examples of behavior I want:

  - "/foo" -> "/foo" - "//foo/" -> "/foo" - "foo/" -> "/foo" - "foo/bar" -> "/foo/bar" - "foo/bar/../baz" -> "/foo/baz" - "foo//bar" -> "/foo/bar" 
+5
source share
1 answer

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

Conclusion:

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

Please note that this is NOT portable. It will not work on Windows machines ...

If you want to use a portable solution, you can use the memory file system , open the Unix file system and use it:

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

Source: https://habr.com/ru/post/1211545/


All Articles