Monday 18 February 2013

How to do a platform-independent path join in Java

Today I had to join a file path with its parent directory path. I could this simply by joining strings with "/", but this solution is not portable to non *nix systems. In Python I would write:
import os.path

parent = "a/b/c"
filename = "efg"
joined = os.path.join(parent, filename)
But what is Java equivalent? It turns out that the best way is to use java.io.File. One can do:
File parent = new File("a/b/c");
File file = new File("efg");
String joined = new File(parent, file).getPath();
The last line is to go back to String world, but possibly you don't have to.