我想使用以下命令访问我当前的工作目录
String current = new java.io.File( "." ).getCanonicalPath();
System.out.println("Current dir:"+current);
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 驱动器不是我的当前目录。在这方面需要帮助。
public class JavaApplication1 {
public static void main(String[] args) {
System.out.println("Working Directory = " +
System.getProperty("user.dir"));
}
}
Path currentRelativePath = Paths.get("");
String s = currentRelativePath.toAbsolutePath().toString();
System.out.println("Current relative path is: " + s);
import java.nio.file.Paths;
Paths.get(".").toAbsolutePath().normalize().toString();
Path path = FileSystems.getDefault().getPath(".");
Path path = FileSystems.getDefault().getPath("Foo.txt");
Path path = FileSystems.getDefault().getPath(".").toAbsolutePath();
File currentDir = new File("");
是什么让您认为c:\ windows \ system32不是您的当前目录? user.dir
属性明确地是 “用户的当前工作目录”。
换句话说,除非您从命令行启动 Java,否则c:\ windows \ system32可能是您的 CWD。也就是说,如果双击启动程序,则 CWD 不太可能是您双击的目录。
编辑 :看来这仅适用于旧的 Windows 和 / 或 Java 版本。
String cwd = new File("").getAbsolutePath();
public class Test {
public static void main(String... args) throws Exception {
URL location = Test.class.getProtectionDomain().getCodeSource().getLocation();
System.out.println(location.getFile());
}
}
this.getClass().getClassLoader().getResource("").getPath()
File getCwd() {
return new File("").getAbsoluteFile();
}
getCwd().getAbsolutePath()