This section java program explain how to get the current working directory(CWD).
Get current working directory in Java
In this section we will discuss about how to get the the current working directory in java. Current working directory means the current working directory where java program execute. In java it is easy to get the current working directory, it can be retrieved by system properties function :
String cwd = System.getProperty("user.dir");
A Properties object of System class describes the configuration of the current working environment. It also include information about current user , the current version of the Java runtime, and the character used to separate component of a file path name. Here, "user.dir" is a user directory
How to get current directory in Java with Example
public class CurrentworkingDirectory { public static void main(String args[]) { String cwd = System.getProperty("user.dir"); System.out.println(" "); System.out.println("Current working directory in Java : " + cwd); } }
Output from the program :
There are two types of path in java they are as follows :
- Canonical path
- Absolute path.
We can get the canonical path by calling getCannonicalPath(), and for absolute path by calling getAbsolutePath() method. Now here is the example using these methods :
import java.io.File; import java.io.IOException; public class CurrentworkingDirectory2 { public static void main(String args[]) throws IOException { File file =new File("."); System.out.println(" "); System.out.println("Canonical path = "+file.getAbsolutePath()); System.out.println("Absolute path = "+file.getCanonicalPath()); } }
Output from the program :