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
}
Answer from fge on Stack OverflowBecause the normalization replaced the .. programs' parent directory.
So you have NIO2 as a sub-folder of OCPJP7.
Similarly, . goes away as it's redundant (indicates current directory within context).
Because the programs element is followed by \\..\\ which means "to go up one directory level". This sequence removes the \\programs\\ part from your path.
Everytime I use them in my projects, I seem to get unintended consequences where the pathing doesn't work as intended.
I'd really like to know how more experienced people use these functions.
Use the built-in String method replaceAll, with a regular expression "/+", replacing one or more slashes with one slash:
path = path.replaceAll("/+", "/");
You could use a File object to output the path specific to the current platform:
String path = "/var/lib/////xen//images///rhel";
path = new File(path).getPath();