Generating a canonical path

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:

  1. 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()!

  2. 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.


If you don't need path canonization but only normalization, in Java 7 you can use java.nio.file.Path.normalize method. According to http://docs.oracle.com/javase/7/docs/api/java/nio/file/Path.html:

This method does not access the file system; the path may not locate a file that exists.

If you work with File object you can use something like this:

file.toPath().normalize().toFile()

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

Tags:

Java

Path