我想使用Java访问我的当前工作目录。
我的代码:
String currentPath = new java.io.File(".").getCanonicalPath();
System.out.println("Current dir:" + currentPath);
String currentDir = System.getProperty("user.dir");
System.out.println("Current dir using System:" + currentDir);
输出:
Current dir: C:\WINDOWS\system32
Current dir using System: C:\WINDOWS\system32
我的输出不正确,因为C驱动器不是我的当前目录。
如何获取当前目录?
这将给你当前工作目录的路径:
Path path = FileSystems.getDefault().getPath(".");
这将为您提供工作目录中名为“Foo.txt”的文件的路径:
Path path = FileSystems.getDefault().getPath("Foo.txt");
编辑:
获取当前目录的绝对路径。
Path path = FileSystems.getDefault().getPath(".").toAbsolutePath();
*更新*
获取当前工作目录:
Path path = FileSystems.getDefault().getPath("").toAbsolutePath();
这将给你当前工作目录的路径:
Path path = FileSystems.getDefault().getPath(".");
这将为您提供工作目录中名为“Foo.txt”的文件的路径:
Path path = FileSystems.getDefault().getPath("Foo.txt");
编辑:
获取当前目录的绝对路径。
Path path = FileSystems.getDefault().getPath(".").toAbsolutePath();
*更新*
获取当前工作目录:
Path path = FileSystems.getDefault().getPath("").toAbsolutePath();