Joining paths in Java

后端 未结 6 1131
有刺的猬
有刺的猬 2021-01-30 02:48

In Python I can join two paths with os.path.join:

os.path.join(\"foo\", \"bar\") # => \"foo/bar\"

I\'m trying to

6条回答
  •  野的像风
    2021-01-30 03:29

    The most reliable, platform-independent way to join paths in Java is by using Path::resolve (as noted in the JavaDoc for Paths::get). For an arbitrary-length array of Strings representing pieces of a path, these could be joined together using a Java Stream:

    private static final String[] pieces = {
        System.getProperty("user.dir"),
        "data",
        "foo.txt"};
    public static void main (String[] args) {
        Path dest = Arrays.stream(pieces).reduce(
        /* identity    */ Paths.get(""),
        /* accumulator */ Path::resolve,
        /* combiner    */ Path::resolve);
        System.out.println(dest);
    }
    

提交回复
热议问题