How to combine paths in Java? How to combine paths in Java? java java

How to combine paths in Java?


Rather than keeping everything string-based, you should use a class which is designed to represent a file system path.

If you're using Java 7 or Java 8, you should strongly consider using java.nio.file.Path; Path.resolve can be used to combine one path with another, or with a string. The Paths helper class is useful too. For example:

Path path = Paths.get("foo", "bar", "baz.txt");

If you need to cater for pre-Java-7 environments, you can use java.io.File, like this:

File baseDirectory = new File("foo");File subDirectory = new File(baseDirectory, "bar");File fileInDirectory = new File(subDirectory, "baz.txt");

If you want it back as a string later, you can call getPath(). Indeed, if you really wanted to mimic Path.Combine, you could just write something like:

public static String combine(String path1, String path2){    File file1 = new File(path1);    File file2 = new File(file1, path2);    return file2.getPath();}


In Java 7, you should use resolve:

Path newPath = path.resolve(childPath);

While the NIO2 Path class may seem a bit redundant to File with an unnecessarily different API, it is in fact subtly more elegant and robust.

Note that Paths.get() (as suggested by someone else) doesn't have an overload taking a Path, and doing Paths.get(path.toString(), childPath) is NOT the same thing as resolve(). From the Paths.get() docs:

Note that while this method is very convenient, using it will imply an assumed reference to the default FileSystem and limit the utility of the calling code. Hence it should not be used in library code intended for flexible reuse. A more flexible alternative is to use an existing Path instance as an anchor, such as:

Path dir = ...Path path = dir.resolve("file");

The sister function to resolve is the excellent relativize:

Path childPath = path.relativize(newPath);


The main answer is to use File objects. However Commons IO does have a class FilenameUtils that can do this kind of thing, such as the concat() method.