English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java flow control

Java array

Java object-oriented (I)

Java object-oriented (II)

Java object-oriented (III)

Java Exception Handling

Java List

Java Queue (queue)

Java Map collection

Java Set collection

Java input/output (I/O)

Java Reader/Writer

Java other topics

Java program to get the current working directory

Comprehensive Java Examples

In this program, you will learn how to get the current working directory in Java.

Example1Get the current working directory

public class CurrDirectory {
    public static void main(String[] args) {
        String path = System.getProperty("user.dir");
        
        System.out.println("Working Directory = "); + path);
    }
}

When running the program, the output is:

Working Directory = C:\Users\Admin\Desktop\currDir

In the above program, we use the System.getProperty() method to get the user.dir program attribute. This will return the directory containing our Java project.

Example2Use Path to Get Current Working Directory

import java.nio.file.Paths;
public class CurrDirectory {
    public static void main(String[] args) {
        String path = Paths.get("").toAbsolutePath().toString();
        System.out.println("Working Directory = "); + path);
    }
}

When running the program, the output is:

Working Directory = C:\Users\Admin\Desktop\currDir

In the above program, we use the get() method of Path to get the current path of the program. This will return to the relative path of the working directory.

Then, we use toAbsolutePath() to change the relative path to an absolute path. Since it returns a Path object, we need to use the toString() method to change it to a string

Comprehensive Java Examples