即使使用获取当前目录的原始解决方案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());
output:
/Users/user/coding/data/foo.txt
来自爪哇Path https://docs.oracle.com/javase/7/docs/api/java/nio/file/Path.html类文档:
如果路径仅由一个名称元素组成,则该路径被视为空路径empty
。使用访问文件empty path is equivalent to accessing the default directory
文件系统的。
Why Paths.get("").toAbsolutePath()
works
当空字符串传递给Paths.get("")
,返回的Path
对象包含空路径。但是当我们打电话时Path.toAbsolutePath()
,它检查路径长度是否大于零,否则使用user.dir
系统属性并返回当前路径。
下面是Unix文件系统的实现代码:UnixPath.toAbsolutePath() http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7-b147/sun/nio/fs/UnixPath.java#UnixPath.toAbsolutePath%28%29
基本上你需要创建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);
Output:
/Users/user/coding/data/foo.txt