Question

How to Get the Current Working Directory in Java

javajava-io

Question

I want to get the current working directory in Java.

Here is the code I am using:

String currentPath = new java.io.File(".").getCanonicalPath();
System.out.println("Current dir: " + currentPath);

String currentDir = System.getProperty("user.dir");
System.out.println("Current dir using System: " + currentDir);

This prints:

Current dir: C:\WINDOWS\system32
Current dir using System: C:\WINDOWS\system32

That output is not what I expected, because C:\WINDOWS\system32 is not the folder I consider my current location.

How does Java determine the current working directory, and what is the correct way to get it?

Short Answer

By the end of this page, you will understand what the current working directory means in Java, why it may be different from the folder you expect, and how to read it using System.getProperty("user.dir"), File, and Path. You will also learn why Java sometimes reports C:\Windows\System32, especially when an application is launched by another process or service.

Concept

In Java, the current working directory is the directory the Java process uses as its base location for relative paths.

That means if your code opens a file like this:

new File("data.txt")

Java interprets data.txt relative to the process working directory.

A key point is this:

  • The current working directory is not necessarily:
    • the folder where your .java file is stored
    • the folder where your .class file is stored
    • the folder where your .jar file is stored
    • the folder you personally think of as the “current folder”

Instead, it is usually determined by whatever started the Java process.

For example:

  • If you run Java from a terminal, it is often the terminal's current folder.
  • If an IDE starts your program, it may use the project root or a configured run directory.
  • If a Windows service or scheduled task starts it, the working directory may become C:\Windows\System32.

That is why your code is returning C:\WINDOWS\system32: Java is correctly reporting the working directory of the running process.

In Java, these two approaches usually reflect the same value:

System.getProperty("user.dir")

and

new File(".").getCanonicalPath()

They are both based on the process working directory.

This matters because many file path bugs come from assuming Java will use the source-code folder or JAR folder automatically. In real programs, it is safer to:

  • know what your working directory is
  • use absolute paths when necessary
  • or build paths from a known location such as configuration or the JAR location

Mental Model

Think of the working directory as the starting point on a map.

If you say:

  • go to data.txt
  • open logs/app.log

Java asks: starting from where?

That starting point is the current working directory.

So if your app starts in:

C:\Windows\System32

then:

new File("logs/app.log")

means:

C:\Windows\System32\logs\app.log

If your app starts in:

C:\Projects\MyApp

then the exact same code means:

C:\Projects\MyApp\logs\app.log

The file path did not change. The starting point changed.

Take Quiz

Syntax and Examples

Basic ways to get the working directory

Using System.getProperty("user.dir")

String workingDir = System.getProperty("user.dir");
System.out.println(workingDir);

This is the most direct way to read Java's current working directory.

Using File

import java.io.File;
import java.io.IOException;

public class Main {
    public static void main(String[] args) throws IOException {
        String path = new File(".").getCanonicalPath();
        System.out.println(path);
    }
}

new File(".") means “this directory”, and getCanonicalPath() resolves it to a clean absolute path.

Using Path and Paths

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

public class Main {
    public static void main(String[] args) {
        Path path = Paths.get("").toAbsolutePath();
        System.out.println(path);
    }
}

This is the modern java.nio.file style and is often easier to work with.

Example: showing all three

import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;

public class Main {
    public static void main(String[] args) throws IOException {
        System.out.println("user.dir      : " + System.getProperty("user.dir"));
        System.out.println("File('.')     : " + new File(".").getCanonicalPath());
        System.out.println("Paths.get("") : " + Paths.get("").toAbsolutePath());
    }
}

In most cases, these will point to the same location.

If you want the JAR or class location instead

Sometimes developers actually want the directory where the program is stored, not the process working directory.

import java.io.File;

public class Main {
    public static void main(String[] args) {
        String jarOrClassDir = new File(
            Main.class.getProtectionDomain()
                      .getCodeSource()
                      .getLocation()
                      .getPath()
        ).getParent();

        System.out.println(jarOrClassDir);
    }
}

Use this only if your goal is to find the application's location, not the working directory.

Step by Step Execution

Consider this code:

import java.io.File;

public class Main {
    public static void main(String[] args) throws Exception {
        System.out.println(System.getProperty("user.dir"));

        File file = new File("notes.txt");
        System.out.println(file.getAbsolutePath());
    }
}

Assume the Java process starts with this working directory:

C:\Projects\Demo

Step 1

Java starts the program.

Step 2

System.getProperty("user.dir") reads the working directory for this process.

Output:

C:\Projects\Demo

Step 3

new File("notes.txt") creates a relative file reference.

At this point, notes.txt is not yet tied to a full path in your head, but Java will resolve it relative to the working directory.

Step 4

file.getAbsolutePath() expands it using the working directory.

Output:

C:\Projects\Demo\notes.txt

Important result

If the program had started in C:\Windows\System32, then the same code would point to:

C:\Windows\System32\notes.txt

That is why the launch location of the Java process matters so much.

Real World Use Cases

Loading configuration files

A program may read:

config/app.properties

This only works correctly if you know what the working directory is.

Writing logs or reports

A script might create files like:

output/report.txt

If the working directory is unexpected, the file may be written to the wrong place.

Running apps from an IDE

When you run a Java app from IntelliJ IDEA, Eclipse, or VS Code, the working directory is often configured by the IDE. Knowing this helps explain why file paths work in the IDE but fail in production.

Windows services and scheduled tasks

These often start programs with C:\Windows\System32 as the working directory. This is a common reason developers see the exact output from your question.

Command-line tools

CLI tools often intentionally use the terminal's current folder so users can run commands like:

java MyTool input.txt

and have input.txt resolved from the folder they are currently in.

Take Quiz

Real Codebase Usage

In real projects, developers usually do more than just print the working directory.

1. Build paths from a known base

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

Path baseDir = Paths.get(System.getProperty("user.dir"));
Path configFile = baseDir.resolve("config").resolve("app.properties");

This is clearer than string concatenation.

2. Use guard clauses for file validation

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

Path file = Paths.get(System.getProperty("user.dir"), "config", "app.properties");

if (!Files.exists(file)) {
    throw new IllegalStateException("Config file not found: " + file);
}

This helps fail early with a useful error message.

3. Avoid depending on the working directory when possible

In larger applications, developers often prefer:

  • command-line arguments
  • environment variables
  • configuration files
  • classpath resources

instead of assuming a specific working directory.

4. Log the resolved path during debugging

System.out.println("Using config file: " + file.toAbsolutePath());

This makes path-related bugs much easier to diagnose.

5. Use classpath resources for bundled files

If a file is packaged inside the application, using the classpath is often better than depending on the working directory.

var stream = Main.class.getResourceAsStream("/app.properties");

That is a different concept from the working directory, but it is often the better choice for bundled resources.

Common Mistakes

Mistake 1: Assuming the working directory is the source folder

Broken assumption:

File file = new File("src/data.txt");

This may work on your machine and fail elsewhere.

Avoid it by

  • using a known configured path
  • using classpath resources for bundled files
  • printing the resolved absolute path during debugging

Mistake 2: Confusing working directory with JAR location

Many beginners expect this:

  • app stored in D:\MyApp
  • therefore working directory should also be D:\MyApp

That is not guaranteed.

The process may be launched from another location.

Mistake 3: Using string concatenation for paths

Less safe:

String path = System.getProperty("user.dir") + "\\config\\app.properties";

Better:

Path path = Paths.get(System.getProperty("user.dir"), "config", "app.properties");

Path handles separators more cleanly.

Mistake 4: Thinking user.dir is always wrong if it shows system32

It may be surprising, but it is often correct for the running process.

If a service launcher or scheduler starts your app there, Java is only reporting reality.

Mistake 5: Trying to change the directory by editing user.dir

Some developers try:

System.setProperty("user.dir", "D:\\MyFolder");

This does not reliably change how the whole process behaves. Do not treat it as a real cd command.

Mistake 6: Forgetting the difference between absolute and relative paths

new File("notes.txt")

is relative.

new File("C:\\Temp\\notes.txt")

is absolute.

Absolute paths do not depend on the working directory.

Comparisons

ApproachWhat it gives youGood forNotes
System.getProperty("user.dir")Process working directoryQuick lookupMost direct way
new File(".").getCanonicalPath()Canonical version of current directoryResolving . and symbolic detailsCan throw IOException
Paths.get("").toAbsolutePath()Absolute path of current directoryModern path handlingWorks well with Path APIs
Main.class.getProtectionDomain().getCodeSource().getLocation()Location of class or JARFinding app installation locationNot the same as working directory

Relative vs absolute paths

Path typeExampleDepends on working directory?
Relativeconfig/app.propertiesYes
AbsoluteC:\\app\\config\\app.propertiesNo

Working directory vs classpath resource

ConceptBest used forExample
Working directoryUser-provided files, CLI input, external configlogs/output.txt
Classpath resourceFiles packaged inside the app/templates/email.txt
Take Quiz

Cheat Sheet

// Most direct
String dir = System.getProperty("user.dir");

// Using File
String dir2 = new java.io.File(".").getCanonicalPath();

// Using Path
java.nio.file.Path dir3 = java.nio.file.Paths.get("").toAbsolutePath();

Rules to remember

  • The current working directory belongs to the running process.
  • It is often set by the terminal, IDE, service manager, or scheduler that launched Java.
  • It is not automatically the source folder, class folder, or JAR folder.
  • Relative paths depend on the working directory.
  • Absolute paths do not.

Common debug line

System.out.println("user.dir = " + System.getProperty("user.dir"));

Safe path building

Path file = Paths.get(System.getProperty("user.dir"), "config", "app.properties");

If you really want the app location instead

Use class or JAR location APIs, not user.dir.

Typical cause of C:\Windows\System32

  • Windows service
  • scheduled task
  • launcher started from system context
  • IDE or tool configured with that working directory

FAQ

Why does Java return C:\Windows\System32 as the current directory?

Because that is often the working directory of the process that launched your Java program, especially for Windows services, scheduled tasks, or system-level launchers.

Is System.getProperty("user.dir") the correct way to get the current directory in Java?

Yes. It is the standard way to get the Java process working directory.

Why does new File(".").getCanonicalPath() match user.dir?

Because . means the current working directory, and Java resolves it using the same process base location.

How do I get the folder where my JAR file is located instead?

Use the class or code source location, such as Main.class.getProtectionDomain().getCodeSource().getLocation().

Can I change the current working directory from inside Java?

Not in the same way as a shell cd command. Changing user.dir is not a reliable process-wide solution.

What is the best modern API for file paths in Java?

Use java.nio.file.Path and Paths because they are clearer and safer than manual string path building.

Why do relative file paths work in my IDE but not after deployment?

Because the working directory used by the IDE may be different from the one used in production.

Take Quiz

Mini Project

Description

Build a small Java program that prints the working directory, creates a path to a configuration file, and checks whether that file exists. This demonstrates how relative paths are resolved and how to use the modern Path API safely.

Goal

Create a program that reports the current working directory and resolves config/app.properties relative to it.

Requirements

  • Print the current working directory.
  • Build a path to config/app.properties using Path or Paths.
  • Print the absolute path of the config file.
  • Check whether the file exists.
  • Print a clear message for both the exists and does-not-exist cases.
Take Quiz

Keep learning

Related questions

View more