Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

How to get a current working directory in Java

abhilash

Problem overview

In this shot, we will discuss how to write a Java program to print the current working directory in which a program is executed.

Solution

We use the Path class from the java.nio.file package and then perform the following steps.

  1. Pass an empty string to the Paths.get() method to get the current relative path.

  2. Use the toAbsolutePath() method to convert the relative path to absolute path.

  3. Call the toString() method on the absolute path to convert the absolute path to string.

steps to print current working directory in java

Code

import java.nio.file.Path;
import java.nio.file.Paths;

public class Main {

    public static void main(String[] args) {
        Path currRelativePath = Paths.get("");
        String currAbsolutePathString = currRelativePath.toAbsolutePath().toString();
        System.out.println("Current absolute path is - " + currAbsolutePathString);
    }
}

RELATED TAGS

java
communitycreator
RELATED COURSES

View all Courses

Keep Exploring