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 OverflowAbout Path normalize() in Java - Stack Overflow
What is an example of using Path.normalize/Path.resolve in your code?
Normalizing slashes from a string path in java - Stack Overflow
java - Generating a canonical path - Stack Overflow
Because 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();
I think you can use the URI class to do this; e.g. if the path contains no characters that need escaping in a URI path component, you can do this.
String normalized = new URI(path).normalize().getPath();
If the path contains (or might contain) characters that need escaping, the multi-argument constructors will escape the path argument, and you can provide null for the other arguments.
Notes:
The above normalizes a file path by treating it as a relative URI. If you want to normalize an entire URI ... including the (optional) scheme, authority, and other components, don't call
getPath()!URI normalization does not involve looking at the file system as File canonicalization does. But the flip side is that normalization behaves differently to canonicalization when there are symbolic links in the path.
Using Apache Commons IO (a well-known and well-tested library)
public static String normalize(String filename)
will do exactly what you're looking for.
Example:
String result = FilenameUtils.normalize(myFile.getAbsolutePath());