在 Python
我可以加入两条路径 os.path.join
:
os.path.join("foo", "bar") # => "foo/bar"
I’m trying to achive the same in Java, without worrying if the OS
is Unix
, Solaris
or Windows
:
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);
}
I was expecting that Path.resolve( )
would join my current directory /home/user/test
with data/foo.txt
making /home/user/test/data/foo.txt
.我错了什么?
原文由 cybertextron 发布,翻译遵循 CC BY-SA 4.0 许可协议
尽管使用
empty String
获取当前目录的原始解决方案有效。但建议对当前目录使用user.home
user.dir
属性,对主目录使用 --- 属性。输出:
来自 Java Path 类文档:
为什么
Paths.get("").toAbsolutePath()
有效当将空字符串传递给
Paths.get("")
时,返回的Path
对象包含空路径。但是当我们调用Path.toAbsolutePath()
时,它会检查路径长度是否大于零,否则它使用user.dir
系统属性并返回当前路径。这是 Unix 文件系统实现的代码: UnixPath.toAbsolutePath()
基本上,您需要在解析当前目录路径后再次创建
Path
实例。此外,我建议使用
File.separatorChar
用于平台独立代码。输出: