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 Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › java › path-normalize-method-in-java-with-examples
Path normalize() method in Java with Examples - GeeksforGeeks
July 30, 2019 - // Java program to demonstrate // java.nio.file.Path.normalize() method import java.nio.file.*; public class GFG { public static void main(String[] args) { // create object of Path Path path = Paths.get("\\.\\.\\core" + "\\file\\binary.java"); // print actual path System.out.println("Actual Path : " + path); // normalize the path Path normalizedPath = path.normalize(); // print normalized path System.out.println("\nNormalized Path : " + normalizedPath); } }
🌐
Java2s
java2s.com › example › java-book › paths-normalizing.html
Java - File Input Output Paths Normalizing
The following code shows some examples of normalizing paths on Windows. import java.nio.file.Path; import java.nio.file.Paths; public class Main { public static void main(String[] args) { Path p1 = Paths.get("C:\\myData\\..\\\\myData\\Main.java"); Path p1n = p1.normalize();/*from www.
🌐
Java2s
java2s.com › Tutorials › Java › java.nio.file › Path › Java_Path_normalize_.htm
Java Tutorial - Java Path.normalize()
In the following code shows how to use Path.normalize() method. //from ww w . j a v a2 s.c om import java.nio.file.Path; import java.nio.file.Paths; public class Main { public static void main(String[] args) { Path path = Paths.get("C:/home/./music/users.txt"); System.out.println("Normalized: " + path.normalize()); } } The code above generates the following result.
🌐
Java2s
java2s.com › Tutorials › Java › java.nio.file › Path › 0300__Path.normalize_.htm
Java IO Tutorial - Java Path.normalize()
In the following code shows how to use Path.normalize() method. /*from w w w. j a v a 2 s .c o m*/ import java.nio.file.Path; import java.nio.file.Paths; public class Main { public static void main(String[] args) { Path path = Paths.get("C:/home/./music/users.txt"); System.out.println("Normalized: " + path.normalize()); } }
🌐
Java2s
java2s.com › Tutorials › Java › IO_How_to › Path › Normalize_a_path.htm
Java I/O How to - Normalize a path
We would like to know how to normalize a path. /*from ww w . j a v a2 s . com*/ import java.net.URI; import java.nio.file.Path; import java.nio.file.Paths; public class Main { public static void main(String[] args) throws Exception { Path path = Paths.get(new URI("C:/home/./music/users.txt")); System.out.println(path); System.out.println("Normalized: " + path.normalize()); } } Back to Path ↑
🌐
Medium
medium.com › @python-javascript-php-html-css › fixing-windows-file-path-issues-in-java-using-path-3dbfff6ed0f8
Fixing Windows File Path Issues in Java Using Path
November 20, 2024 - Using the Path.normalize() method, you can streamline paths to their simplest form, reducing potential errors when working with both local files and external APIs. This approach is especially important when paths come from different environments ...
🌐
Tabnine
tabnine.com › home › code library
Code Library - Tabnine
July 25, 2024 - Get the answers and suggestions you need from our AI code assistant. Get started in minutes with a free 90 day trial of Tabnine Pro.
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › nio › file › Path.html
Path (Java Platform SE 8 )
April 21, 2026 - This method does not access the file system; the path or its parent may not exist. Furthermore, this method does not eliminate special names such as "." and ".." that may be used in some implementations. On UNIX for example, the parent of "/a/b/c" is "/a/b", and the parent of "x/y/." is "x/y". This method may be used with the normalize method, to eliminate redundant names, for cases where shell-like navigation is required.
Find elsewhere
🌐
GitHub
gist.github.com › jgregorio0 › 4faf14a409561c5ef59de1e1964db8d0
normalizeFile.md · GitHub
private static final String REGEX_NON_ASCII = "[^\\p{ASCII}]"; /** * Elimina tildes y sustituye espacios por "-" * @param filename * @return */ public static String normalizeFilename(String filename) { if (StringUtils.isBlank(filename)) { return filename; } return Normalizer.normalize(filename, Normalizer.Form.NFD) .replaceAll(REGEX_NON_ASCII, "") .replaceAll(" ", "-"); } java.nio.file.Path to normalize pathname ·
🌐
Jenkov
jenkov.com › tutorials › java-nio › path.html
Java NIO Path
Normalizing means that it removes all the . and .. codes in the middle of the path string, and resolves what path the path string refers to. Here is a Java Path.normalize() example:
🌐
Oracle
docs.oracle.com › javase › 7 › docs › api › java › nio › file › Path.html
Path (Java Platform SE 7 )
This method does not access the file system; the path or its parent may not exist. Furthermore, this method does not eliminate special names such as "." and ".." that may be used in some implementations. On UNIX for example, the parent of "/a/b/c" is "/a/b", and the parent of "x/y/." is "x/y". This method may be used with the normalize method, to eliminate redundant names, for cases where shell-like navigation is required.
🌐
Reddit
reddit.com › r/learnjavascript › what is an example of using path.normalize/path.resolve in your code?
r/learnjavascript on Reddit: What is an example of using Path.normalize/Path.resolve in your code?
March 5, 2020 -

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.

Top answer
1 of 1
3
Let's see what they say they do: Path.normalize The path.normalize() method normalizes the given path, resolving '..' and '.' segments. "Normalize" here means make consistent. "Resolve" means work out what the symbols represent, . is the current directory and .. is up one directory. When multiple, sequential path segment separation characters are found (e.g. / on POSIX and either \ or / on Windows), they are replaced by a single instance of the platform-specific path segment separator (/ on POSIX and \ on Windows). Trailing separators are preserved. Different operating systems use different characters in paths. For example, C:\Users\jrandm\ on Windows and /home/jrandm/ on Linux. Part of normalizing -- making consistent -- is making sure the same path separator (the slash) is used. Node knows when it is running on Windows or a POSIX system (this includes Linux, BSD, and Mac). If the path is a zero-length string, '.' is returned, representing the current working directory. I think that's self-explanatory. Path.resolve The path.resolve() method resolves a sequence of paths or path segments into an absolute path. As in normalize, "resolve" here means to take any symbols and convert it into a full, or absolute, path. That means it is completely qualified: all of the /./ and /../ parts are applied so it is only the directory names and file. /foo/bar/.././././baz becomes /foo/baz. The given sequence of paths is processed from right to left, with each subsequent path prepended until an absolute path is constructed. [example cut] This means it starts on the left side and moves right, condensing the .s until they're all gone. If after processing all given path segments an absolute path has not yet been generated, the current working directory is used. If for some reason it fails to remove all the .s, this function falls back to the current working directory. That is defined as part of the environment when you run the node program. The resulting path is normalized and trailing slashes are removed unless the path is resolved to the root directory. The result of the resolution process is passed through normalize, described above, and any trailing slashes are removed unless it is the root directory (meaning something like / on POSIX or C:\ on Windows).
🌐
Baeldung
baeldung.com › home › java › java io › java nio2 path api
Java NIO2 Path API | Baeldung
January 8, 2024 - You might have a situation where ... two have redundancies while the last one does not. Normalizing a path involves removing redundancies in it....
🌐
Dev.java
dev.java › learn › java-io › file-system › path
Working with Paths - Dev.java
January 25, 2023 - Perhaps a server is configured ... "/." notation from the path. ... The normalize() method removes any redundant elements, which includes any "." or "directory/.." occurrences....
🌐
Oracle
docs.oracle.com › en › java › javase › 20 › docs › api › java.base › java › nio › file › Path.html
Path (Java SE 20 & JDK 20)
July 10, 2023 - This method does not access the file system; the path or its parent may not exist. Furthermore, this method does not eliminate special names such as "." and ".." that may be used in some implementations. On UNIX for example, the parent of "/a/b/c" is "/a/b", and the parent of "x/y/." is "x/y". This method may be used with the normalize method, to eliminate redundant names, for cases where shell-like navigation is required.
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › api › java.net.uri.normalize
URI.Normalize Method (Java.Net) | Microsoft Learn
This prevents a relative URI with a path such as "a:b/c/d" from later being re-parsed as an opaque URI with a scheme of "a" and a scheme-specific part of "b/c/d". <b>(Deviation from RFC&nbsp;2396)</b> ... A normalized path will begin with one or more ".." segments if there were insufficient non-".." segments preceding them to allow their removal.