How to combine paths in Java?
Asked Answered
S

12

455

Is there a Java equivalent for System.IO.Path.Combine() in C#/.NET? Or any code to accomplish this?

This static method combines one or more strings into a path.

Speedwriting answered 5/1, 2009 at 6:6 Comment(1)
This SO question might help.Avra
A
507

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();
}
Ayana answered 5/1, 2009 at 7:29 Comment(11)
Beware of absolute paths. The .NET version will return path2 (ignoring path1) if path2 is an absolute path. The Java version will drop the leading / or \ and treat it as a relative path.Sinful
To satisfy @Sinful [important] comment you can add File f2 = new File(path2); if (f2.isAbsolute()) return f2; somewhere in your function.Gretchen
This is inefficient and unclean, as it requires creating a File object, and then back to string.Lignite
@Hugo: So it wastes a whole two objects? Shocking! Looks pretty clean to me, to be honest... it keeps the logic for relative file names where it belongs, in the File class.Ayana
still, I'd argue that a constructor new File(String... pathElements) would be cleaner, possible with an added new File(File basepath, String... pathElements)Neoclassicism
new File("a/b/c", "../c2") yields "a/b/c/../c2". How do I get "a/b/c2" instead?Brevier
@modosansreves: Look at File.getCanonicalPath.Ayana
@SargeBorsch: Well C# is just a language. You could easily create your own equivalent of File in C# if you wanted to. (I'm assuming you mean the existence of File is a benefit, which I'd agree with.)Ayana
@SargeBorsch: These days, Java works more with Path objects than with File... but in .NET, there's always FileInfo and DirectoryInfo if you want. Regardless, this isn't a matter for C#, given that it's only a language...Ayana
Using objects for file names is unnecessarily messy. Evidence: trying to work with them in PowerShell. I'm constantly having to convert to strings so I can pass it to some command line tool, and I end up with a bunch of boiler plate just trying to get it to spit out the right string especially since there are a bunch of different types that can be used for file objects. I used to think you "should use an object," too, but there's no real gain that I've ever seen.Fougere
@jpmc26: That's only evidence of it being a pain in a specific setting. I've found it very useful in Java for a variety of other needs which don't require the value as a string.Ayana
M
192

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);
Monopolize answered 19/11, 2013 at 10:50 Comment(4)
"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." Sure, but you have to use some equivalent function to generate a Path object (because it's an interface and can't be instantiated directly). So at some point you are creating a reference to the underlying FS. I think the docs are misleading here.Incandescence
@éclairevoyant They mean the reference will be to the default FS, rather than the FS that the parent path refers to. Unlike most OSes, Java supports multiple, separate filesystems. Eg, a zip file or cloud storage can be exposed as a FS object. It’s a cool, although not-widely-used-yet feature.Monopolize
All modern OSes should support multiple filesystems, but that's besides the point. If not Paths.get(...) how would one create a Path without using an existing Path? (Maybe this should be a new question.)Incandescence
@éclairevoyant FileSystem::getPath I should have said Java supports multiple FS namespaces (one per FS object). OSes have a single namespace.Monopolize
T
47

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.

Trogon answered 5/1, 2009 at 13:5 Comment(2)
FilenameUtils.concat, to be precise. commons.apache.org/proper/commons-io/apidocs/org/apache/commons/…Angers
If youre working with something like JSF, youre definitly want to keep it String-based as all the Paths you 'll get will be String-based.Slyke
C
28

platform independent approach (uses File.separator, ie will works depends on operation system where code is running:

java.nio.file.Paths.get(".", "path", "to", "file.txt")
// relative unix path: ./path/to/file.txt
// relative windows path: .\path\to\filee.txt

java.nio.file.Paths.get("/", "path", "to", "file.txt")
// absolute unix path: /path/to/filee.txt
// windows network drive path: \\path\to\file.txt

java.nio.file.Paths.get("C:", "path", "to", "file.txt")
// absolute windows path: C:\path\to\file.txt
Corn answered 9/8, 2017 at 14:43 Comment(0)
B
18

I know its a long time since Jon's original answer, but I had a similar requirement to the OP.

By way of extending Jon's solution I came up with the following, which will take one or more path segments takes as many path segments that you can throw at it.

Usage

Path.combine("/Users/beardtwizzle/");
Path.combine("/", "Users", "beardtwizzle");
Path.combine(new String[] { "/", "Users", "beardtwizzle", "arrayUsage" });

Code here for others with a similar problem

public class Path {
    public static String combine(String... paths)
    {
        File file = new File(paths[0]);

        for (int i = 1; i < paths.length ; i++) {
            file = new File(file, paths[i]);
        }

        return file.getPath();
    }
}
Boelter answered 5/2, 2012 at 9:31 Comment(0)
S
12

To enhance JodaStephen's answer, Apache Commons IO has FilenameUtils which does this. Example (on Linux):

assert org.apache.commons.io.FilenameUtils.concat("/home/bob", "work\\stuff.log") == "/home/bob/work/stuff.log"

It's platform independent and will produce whatever separators your system needs.

Stubby answered 14/11, 2010 at 13:31 Comment(0)
S
6

Late to the party perhaps, but I wanted to share my take on this. I prefer not to pull in entire libraries for something like this. Instead, I'm using a Builder pattern and allow conveniently chained append(more) calls. It even allows mixing File and String, and can easily be extended to support Path as well. Furthermore, it automatically handles the different path separators correctly on both Linux, Macintosh, etc.

public class Files  {
    public static class PathBuilder {
        private File file;

        private PathBuilder ( File root ) {
            file = root;
        }

        private PathBuilder ( String root ) {
            file = new File(root);
        }

        public PathBuilder append ( File more ) {
            file = new File(file, more.getPath()) );
            return this;
        }

        public PathBuilder append ( String more ) {
            file = new File(file, more);
            return this;
        }

        public File buildFile () {
            return file;
        }
    }

    public static PathBuilder buildPath ( File root ) {
        return new PathBuilder(root);
    }

    public static PathBuilder buildPath ( String root ) {
        return new PathBuilder(root);
    }
}

Example of usage:

File root = File.listRoots()[0];
String hello = "hello";
String world = "world";
String filename = "warez.lha"; 

File file = Files.buildPath(root).append(hello).append(world)
              .append(filename).buildFile();
String absolute = file.getAbsolutePath();

The resulting absolute will contain something like:

/hello/world/warez.lha

or maybe even:

A:\hello\world\warez.lha
Sidran answered 12/2, 2019 at 10:54 Comment(0)
K
4

If you do not need more than strings, you can use com.google.common.io.Files

Files.simplifyPath("some/prefix/with//extra///slashes" + "file//name")

to get

"some/prefix/with/extra/slashes/file/name"
Khrushchev answered 3/4, 2017 at 12:44 Comment(0)
A
2

Here's a solution which handles multiple path parts and edge conditions:

public static String combinePaths(String ... paths)
{
  if ( paths.length == 0)
  {
    return "";
  }

  File combined = new File(paths[0]);

  int i = 1;
  while ( i < paths.length)
  {
    combined = new File(combined, paths[i]);
    ++i;
  }

  return combined.getPath();
}
Adjoint answered 7/12, 2010 at 18:36 Comment(0)
J
1

This also works in Java 8 :

Path file = Paths.get("Some path");
file = Paths.get(file + "Some other path");
Juno answered 16/6, 2019 at 2:26 Comment(0)
U
0

This solution offers an interface for joining path fragments from a String[] array. It uses java.io.File.File(String parent, String child):

    public static joinPaths(String[] fragments) {
        String emptyPath = "";
        return buildPath(emptyPath, fragments);
    }

    private static buildPath(String path, String[] fragments) {
        if (path == null || path.isEmpty()) {
            path = "";
        }

        if (fragments == null || fragments.length == 0) {
            return "";
        }

        int pathCurrentSize = path.split("/").length;
        int fragmentsLen = fragments.length;

        if (pathCurrentSize <= fragmentsLen) {
            String newPath = new File(path, fragments[pathCurrentSize - 1]).toString();
            path = buildPath(newPath, fragments);
        }

        return path;
    }

Then you can just do:

String[] fragments = {"dir", "anotherDir/", "/filename.txt"};
String path = joinPaths(fragments);

Returns:

"/dir/anotherDir/filename.txt"

Unbar answered 4/10, 2019 at 15:23 Comment(0)
H
0

Assuming all given paths are absolute paths. you can follow below snippets to merge these paths.

String baseURL = "\\\\host\\testdir\\";
String absoluteFilePath = "\\\\host\\testdir\\Test.txt";;
String mergedPath = Paths.get(baseURL, absoluteFilePath.replaceAll(Matcher.quoteReplacement(baseURL), "")).toString();

output path is \\host\testdir\Test.txt.

Haricot answered 8/6, 2021 at 13:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.