当我尝试下面的代码时,它没有返回当前目录。相反,它仅返回 .
,即点。
String current = System.getProperty("user.dir");
System.out.println("Current working directory in Java : " + current);
输出:
Current working directory in Java :.
答案 0 :(得分:0)
价值的来源似乎是特定于平台的,但肯定是 .
,即"dot"
并不是特别有用的结果。不确定如何处理,但是如果您的主要目的是获取有意义的值,则可以根据this documentation使用以下任一选项:
getCanonicalPath()
getCanonicalFile()
getAbsolutePath()
getAbsoluteFile()
基于 Windows操作系统的示例:
理想场景:
代码块:
System.out.println("user.dir: "+System.getProperty("user.dir"));
控制台输出:
user.dir: C:\Users\AtechM_03\LearnAutmation\learn-automation
替代:
代码块:
String user_dir = System.getProperty("user.dir");
File pwdDir = new File(user_dir);
System.out.println("Current working directory in Java : " + pwdDir.getCanonicalPath());
System.out.println("Current working directory in Java : " + pwdDir.getCanonicalFile());
System.out.println("Current working directory in Java : " + pwdDir.getAbsolutePath());
System.out.println("Current working directory in Java : " + pwdDir.getAbsoluteFile());
控制台输出:
Current working directory in Java : C:\Users\AtechM_03\LearnAutmation\learn-automation
Current working directory in Java : C:\Users\AtechM_03\LearnAutmation\learn-automation
Current working directory in Java : C:\Users\AtechM_03\LearnAutmation\learn-automation
Current working directory in Java : C:\Users\AtechM_03\LearnAutmation\learn-automation