Explain Codes LogoExplain Codes Logo

Does Java have a path joining method?

java
path-engineering
best-practices
utility-method
Alex KataevbyAlex Kataev·Feb 5, 2025
TLDR

Java provides Paths.get() from the java.nio.file.Paths class for efficient path concatenation. For example:

Path combinedPath = Paths.get("/my/directory", "file.txt"); System.out.println(combinedPath);

This prints out: /my/directory/file.txt

Alternatively, you can append to an existing Path object using the resolve method:

Path path = Paths.get("/my/directory").resolve("file.txt"); System.out.println(path);

This returns: /my/directory/file.txt

Bulletproof Path Joining

Let's be real, bugs love to feast on edge cases. Luckily for us, java.nio.file.Paths allows us to join paths efficiently and incident-free. Here's how:

  • Null or Empty Strings: Who needs a pesky NullPointerException ruining the party? Before you combine your paths, vet them to ensure they're not null or empty.
public static Path safeJoin(String first, String... more) { if (first == null || first.isEmpty()) { throw new IllegalArgumentException("C'mon, give me at least some crumbs to work with"); } return Paths.get(first, more); }
  • Duplicate Separators: Unwanted separators are the party crashers we didn't invite. If you find yourself manually joining strings, you might want to check for duplicated separators. Apache Commons IO jumps in again with FilenameUtils.concat!
String joined = FilenameUtils.concat("/my/path", "/file.txt"); // Handles separators like a champ.
  • System-dependent Separators: Saying `File.separator` or Path is like asking for universal peace in code world. It works regardless of your operating system.
String crossPlatformPath = "my" + File.separator + "path";

All set? Fasten your seatbelt; we're about to dive deeper!

Using System Properties

The system essentially has a "Draw my Life" system properties video where it stores all the trivia details. Let's see how we can leverage Java's system properties for path manipulations:

  • java.io.tmpdir can get you the default temporary file path.
String tempDir = System.getProperty("java.io.tmpdir"); Path tempFile = Paths.get(tempDir, "myTempFile.txt");
  • The current working directory? user.dir has got you covered!
String workingDir = System.getProperty("user.dir"); Path logFile = Paths.get(workingDir, "logs", "app.log");

Pro-tip: Always sanitize inputs, ensuring paths are safe and valid. We do coding, not arson.

Your One-stop-shop Utility Method

A static utility method works like a coffee machine - put in the right inputs, and it will serve your requested output. Just make sure to handle edge cases.

public class PathUtils { public static Path joinPaths(String... paths) { String result = Arrays.stream(paths) .filter(Objects::nonNull) // Ghost paths, you shall not pass! .map(PathUtils::removeUnwantedSeparators) // Bye bye, unwelcome separators! .collect(Collectors.joining(File.separator)); return Paths.get(result); } private static String removeUnwantedSeparators(String path) { // Logic to remove leading/trailing or duplicate separators } }