tags:

views:

2299

answers:

3

Hi, Is there a java equivalent for System.IO.Path.Combine of C#? Or any code to accomplish this?

A: 

This SO question might help.

Jim Blizard
I didn't know about relativize() method. Thanks for the link, Jim.
Adeel Ansari
I don't think its similar to System.IO.Path.Combine, though.
Adeel Ansari
+24  A: 

Rather than keeping everything string-based, if you use java.io.File, you can do:

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();
}
Jon Skeet
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.
finnw
Why does java use `File` for directories, instead of a separate `Directory` class?
Matthew
@Matthew: I'm not sure, to be honest...
Jon Skeet
@Matthew - because a directory is a file. It's file whose contents define the children of that dir, their location on disk, permissions, etc.
Don
+1  A: 

The main answer is to use File objects. However Commons IO does have a class FilenameUtils that can do this kind of thing.

JodaStephen