在 Python
中,我可以使用 os.path.join
连接两条路径:
os.path.join("foo", "bar") # => "foo/bar"
我正在尝试在 Java 中实现相同的目标,而不用担心 OS
是 Unix
、Solaris
还是 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);
}
我期待 Path.resolve( )
将加入我当前的目录 /home/user/test
和 data/foo.txt
制作 /home/user/test/data/foo.txt
。
我哪里错了?
最佳答案
即使使用 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类文档:
A Path is considered to be an empty path if it consists solely of one name element that is
empty
. Accessing a file using anempty path is equivalent to accessing the default directory
of the file system.
为什么 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
关于java - 在 Java 中加入路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34459486/