Java中的连接路径

网络纺织

Python我可以加入两个路​​径os.path.join

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

我想才达到在Java中一样,不用担心,如果OSUnixSolarisWindows

public static void main(String[] args) {
    Path currentRelativePath = Paths.get("");
    String current_dir = currentRelativePath.toAbsolutePath().toString();
    String filename = "data/foo.txt";
    Path filepath = currentRelativePath.resolve(filename);

    // "data/foo.txt"
    System.out.println(filepath);

}

我期待那Path.resolve( )会加入我的当前目录/home/user/testdata/foo.txt制作/home/user/test/data/foo.txt我怎么了?

YoungHobbit:

即使使用该方法获得当前目录的原始解决方案也是如此empty String但是建议将user.dir属性用于当前目录和user.home主目录。

Path currentPath = Paths.get(System.getProperty("user.dir"));
Path filePath = Paths.get(currentPath.toString(), "data", "foo.txt");
System.out.println(filePath.toString());

输出:

/Users/user/coding/data/foo.txt

从Java Path类文档中:

如果Path仅由一个name元素组成,则将其视为空路径empty使用empty path is equivalent to accessing the default directory的文件系统访问文件。


为什么Paths.get("").toAbsolutePath()工作

当将空字符串传递给时Paths.get(""),返回的Path对象包含空路径。但是,当我们调用时Path.toAbsolutePath(),它将检查路径长度是否大于零,否则它将使用user.dir系统属性并返回当前路径。

这是Unix文件系统实现的代码:UnixPath.toAbsolutePath()


基本上Path,一旦您解析了当前目录路径,就需要再次创建该实例。

我也建议使用File.separatorChar平台无关的代码。

Path currentRelativePath = Paths.get("");
Path currentDir = currentRelativePath.toAbsolutePath(); // <-- Get the Path and use resolve on it.
String filename = "data" + File.separatorChar + "foo.txt";
Path filepath = currentDir.resolve(filename);

// "data/foo.txt"
System.out.println(filepath);

输出:

/Users/user/coding/data/foo.txt

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章