小编典典
即使使用该方法获得当前目录的原始解决方案也是如此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系统属性并返回当前路径。
基本上Path,一旦您解析了当前目录路径,就需要再次创建该实例。
我也建议使用File.separatorChar平台无关的代码。
Path currentRelativePath = Paths.get("");
Path currentDir = currentRelativePath.toAbsolutePath(); //
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
2020-12-03