How to get user’s current working directory or Java Execution Path

In this quick coding tip we will see how to get user’s current working directory or Java execution path using java.lang.System class.

Java code for getting user’s current working directory or Java execution path

Java code for getting user's current working directory or Java execution path
package com.javabrahman.corejava;
public class UserCurrentWorkingDirectory {
  public static void main(String args[]){
    String currentDirectory = System.getProperty("user.dir");
    System.out.println("User's current working directory is: "+currentDirectory);
  }
}
 OUTPUT of the above code
User’s current working directory is: C:\JavaBrahman\workspaces\javabrahman\Java8

Quick explanation of the above code

  • The above code uses java.lang.System class which as its name suggests is a system-level class used for fetching environment specific details among other system-wide utilities that it also provides.
  • System’s static method getProperty() is used to retrieve environment specific values with the syntax –
    static String getProperty(String key)
  • For getting the user’s current working directory we need to pass the designated key for the same which is ‘user.dir
  • In return I got the local Windows directory path for my system which has been printed above as output.

 

Digiprove sealCopyright © 2014-2019 JavaBrahman.com, all rights reserved.