即使使用该方法获得当前目录的原始解决方案也是如此
emptyString。但是建议将该
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 accessingthe 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



