Hi, Is there a java equivalent for System.IO.Path.Combine of C#? Or any code to accomplish this?
I didn't know about relativize() method. Thanks for the link, Jim.
Adeel Ansari
2009-01-05 06:51:19
I don't think its similar to System.IO.Path.Combine, though.
Adeel Ansari
2009-01-05 06:59:11
+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
2009-01-05 07:29:27
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
2010-02-12 18:17:06
Why does java use `File` for directories, instead of a separate `Directory` class?
Matthew
2010-04-08 01:10:48
@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
2010-06-16 08:06:21
+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
2009-01-05 13:05:10