Search code examples
javapathnioseparator

Should I care about File#separator for Path#resolve(String)


I'm writing a method copies files from HDFS to local disk.

String pathString = ".../.../..."; slash-separated HDFS path string
Path directory = ...;

Path target = directory.resolve(pathString);

Now should I replace all slashes with File#separator with pathString?

In other words,

Can I do following even with Windows?

Path base = Path.get(a, b);
String pathname = "c/d";
Path target = base.resolve(pathname); // Will work as a\b\c\d? 

Solution

  • File#separator is not necessary if you want to keep your path logic platform-agnostic. An easier way to do it is to build the child path with Paths.get() and resolve that. E.g.,:

    Path path = Paths.get("a", "b", "c");
    Path directory = ...;
    
    Path target = directory.resolve(path);