获取Java中的当前工作目录

方法java.lang.System.getProperty()用于获取系统属性。此系统属性由作为方法参数的键指定。要获取当前的工作目录,使用的键是user.dir。

演示此的程序如下所示-

示例

public class Demo {
   public static void main(String[] argv) throws Exception {
      String currentDirectory = System.getProperty("user.dir");
      System.out.println("The current working directory is " + currentDirectory);
   }
}

上面程序的输出如下-

输出结果

The current working directory is c:\JavaProgram

现在让我们了解上面的程序。

通过使用键user.dir和方法java.lang.System.getProperty()获得当前工作目录。然后打印当前工作目录。证明这一点的代码片段如下-

String currentDirectory = System.getProperty("user.dir");
System.out.println("The current working directory is " + currentDirectory);