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.

2 comments:

  1. Thanks for commenting too. Keep sharing such an informative blogs with us..
    thejacketzone

    ReplyDelete
  2. Thanks for your article. Looking forward to your next post. I wish you all the best in the upcoming updates. This article is really interesting and useful. I have an profile about APM. Click her to go Action Per Minute Test profile.

    ReplyDelete