Use:

Paths.get(...).normalize().toString()

Another solution woul be:

Paths.get(...).toAbsolutePath().toString()

However, you get strange results: Paths.get("/tmp", "foo").toString() returns /tmp/foo here. What is your filesystem?

Answer from fge on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › java › path-tostring-method-in-java-with-examples
Path toString() method in Java with Examples - GeeksforGeeks
April 14, 2023 - The Java Path interface was added to Java NIO in Java 7. toString() method of java.nio.file.Path used to return the string representation of this path. If this path was created by converting a path string using the getPath method then the path string returned by this method may differ from the original String used to create the path.
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › nio › file › Path.html
Path (Java Platform SE 8 )
April 21, 2026 - In the simplest case, the given ... implementation dependent and therefore unspecified. ... Converts a given path string to a Path and resolves it against this Path in exactly the manner specified by the resolve method....
🌐
Medium
medium.com › @AlexanderObregon › javas-paths-get-method-explained-9586c13f2c5c
Java’s Paths.get() Method Explained | Medium
September 8, 2024 - Explore how Java's Paths.get() method simplifies cross-platform file management by converting strings or URIs into file paths with ease.
🌐
Dev.java
dev.java › learn › java-io › file-system › path
Working with Paths - Dev.java
January 25, 2023 - The method that takes a String converts the String to a Path and then calls the other method.
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › nio › file › Paths.html
Paths (Java Platform SE 8 )
April 21, 2026 - 8 ... This class consists exclusively of static methods that return a Path by converting a path string or URI. ... Converts a path string, or a sequence of strings that when joined form a path string, to a Path. If more does not specify any elements then the value of the first parameter is ...
Top answer
1 of 8
43

Nearly every major programming language has a library to handle the directory separators for you. You should leverage them. This will simplify your code and prevent bugs.

In my experience, the usual reason for combining strings like this is that they come from different sources. Sometimes it's different pieces from a configuration file. Sometimes it's a constant combining with a function argument. In any and all cases, when they come from different sources, you have to consider several different possible cases regarding the separators on the ends to be combined:

  • Both ends could have a separator: "images/" and "/sounds"
  • Only one has a separator: "images" and "/sounds" or "images/" and "sounds"
  • Neither has a separator: "images" and "sounds"

The fact each part comes from a different source means each source might have its own ideas about what conventions to follow, if someone gave any thought to it at all! Whatever is calling your code should not have to worry about this. Your code should handle all cases because someone will violate your convention. This will result in wasted time investigating the cause of an error and making a fix. I have had several unpleasant occasions where a coworker made an assumption about how paths should be formatted in a configuration file, meaning I had to go hunt down the code and figure out what they were expecting (or fix the code).

Most major languages provide a method to do this for you that already handles many of the cases:

  • os.path.join for Python
  • File.join for Ruby
  • Path.join for Node.js
  • Paths.get for Java (7 and up)
  • Path.Combine for .NET
  • filesystem::path.operator+ for C++17

There is a caveat with these. A number of these seem to assume that a leading directory separator in the second argument refers to a root path and that this means the first argument should be dropped entirely. I don't know why this is considered useful; for me, it just causes problems. I've never wanted to combine two path portions and end up with the first part being dropped. Read the documentation carefully for special cases, and if necessary, write a wrapper that does what you want with these instead of their special handling.

This additionally helps if you have any need for supporting different operating systems. These classes almost ubiquitously account for choosing the correct separator. The libraries usually have a way of normalizing paths to fit the OS conventions, as well.

In the event that your programming language does not have a readily available library, you should write a method that handles all these cases and use it liberally and across projects.

This falls into the category of "don't make assumptions" and "use tools that help you."

2 of 8
38

In Java, the answer would be "neither of the above". Best practice would be to assemble pathnames using the java.io.File class; e.g.

File assets = new File("images");
File sounds = new File(assets, "sounds");

The File class also takes care of platform-specific pathname separators.

There is a separate issue of whether your pathname should start with a slash or not. But that is more to do with correctness than best practice. A pathname that starts with a slash means something different to a pathname that doesn't!!


There isn't explicit support for pathname handling in the core (ECMA) Javascript library, but (at least) Node.js provides support via the Path module.

🌐
OpenJDK
cr.openjdk.org › ~jlaskey › templates › docs › api › java.base › java › nio › file › Paths.html
Paths (Java SE 21 & JDK 21 [ad-hoc build])
It is recommended to obtain a Path via the Path.of methods instead of via the get methods defined in this class as this class may be deprecated in a future release. ... Converts a path string, or a sequence of strings that when joined form a path string, to a Path.
Find elsewhere
🌐
W3Schools
w3schools.com › java › java_ref_string.asp
Java String Reference
Java Examples Java Videos Java Compiler Java Exercises Java Quiz Java Code Challenges Java Practice Problems Java Server Java Syllabus Java Study Plan Java Interview Q&A ... The String class has a set of built-in methods that you can use on strings. ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com
🌐
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 - Together, these techniques create a robust system for managing file paths in any Java application. 🛡️ ... Using Paths.get() ensures paths are generated using the correct separator for the current operating system. How can I convert a relative path to an absolute path?
🌐
Jérôme Pilliet
igm.univ-mlv.fr › ~carayol › javadoc-19 › api › java.base › java › nio › file › Paths.html
Paths (Java SE 19 & JDK 19)
This method simply invokes Path.of(String, String...) with the given parameters. ... Converts the given URI to a Path object.
🌐
Kotlin
kotlinlang.org › api › core › kotlin-stdlib › kotlin.io.path › -path.html
Path | Core API – Kotlin Programming Language
Converts the name sequence specified with the base path string and a number of subpaths additional names to a Path object of the default filesystem.
🌐
HappyCoders.eu
happycoders.eu › java › file-and-directory-names-file-path-paths
File and Directory Names in Java: File, Path, Paths
November 29, 2024 - In contrast, there can be more than one absolute path to the same file. An example: For the file /var/log/syslog, this String is also the "canonical path". The same String is also an absolute path. However, there are other absolute paths, such as ... Although the interface of java.nio.file.Path ...
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › api › java.nio.filenio.paths.get
Paths.Get Method (Java.Nio.FileNio) | Microsoft Learn
[<Android.Runtime.Register("get", "(Ljava/lang/String;[Ljava/lang/String;)Ljava/nio/file/Path;", "", ApiSince=26)>] static member Get : string * string[] -> Java.Nio.FileNio.IPath ... Portions of this page are modifications based on work created and shared by the Android Open Source Project and used according to terms described in the Creative Commons 2.5 Attribution License.
🌐
Tudelft
weblab.tudelft.nl › docs › java › 22 › api › java.base › java › nio › file › Paths.html
Paths (Java SE 22 & JDK 22)
This method simply invokes Path.of(String, String...) with the given parameters. ... Converts the given URI to a Path object.