Recursively Combine a File Path in Java

I was looking for a built-in way to combine file paths in Java like the Path.Combine() function in C#; none exist, so I decided to write my own. It’s not hard, but I thought I’d share it since it seems to be a popular question online.

public static String combinePath(String ... paths) {
    String fullPath = "";
    
    for(String path : paths) {
        fullPath = combinePathRecursive(fullPath, path);
    }
    
    return fullPath;
}
    
private static String combinePathRecursive(String path1, String path2) {
    File file1 = new File(path1);
    File file2 = new File(file1, path2);
    return file2.getPath();
}

That’s it! The function will recursively combine the strings until you get the full path.

Example:

System.out.println(combinePath("foo", "bar", "foobar.txt"));
// Will print "foo/bar/foobar.txt".

Posted in Snippets.