Skip to lesson

Relative and absolute paths

I'm on:

Showing steps for Windows. They are marked “On Windows” below.

A relative path such as data/marks.txt does not say where it starts. Java always starts it from one folder, the working directory, and most "file not found" surprises come from not knowing which folder that is.

The working directory and user.dir

An absolute path starts from the root of the file system; a relative path starts from the program's current working folder.

The working directory is the folder your program was started from. Java reads it once at start-up and stores it in the system property user.dir: System.getProperty("user.dir").

A folder tree: root, Users, priya, then college-projects (the working directory), data and marks.txt. The absolute path starts at the root. The relative path data/marks.txt starts at the working directory.

On Windows

In PowerShell, Get-Location shows the folder you are in. If you start Java from here, user.dir is C:\Users\Priya\college-projects, and the relative path data/marks.txt means C:\Users\Priya\college-projects\data\marks.txt.

Windows PowerShell
PS C:\Users\Priya\college-projects> Get-LocationPath
----
C:\Users\Priya\college-projects

Example 1 · Where is the working directory?

WorkingDirDemo.javaJava
import java.nio.file.Path;
public class WorkingDirDemo {    public static void main(String[] args) {        String workingDir = System.getProperty("user.dir");        System.out.println("Working directory: " + workingDir);
        Path marks = Path.of("marks.txt");        Path start = Path.of(workingDir);        System.out.println(marks + " is absolute? " + marks.isAbsolute());        System.out.println("user.dir is absolute? " + start.isAbsolute());        System.out.println("Root of user.dir: " + start.getRoot());    }}
Sample output (Windows; your folder will differ, and macOS shows a root of /)
Working directory: C:\Users\Asha\java-practice
marks.txt is absolute? false
user.dir is absolute? true
Root of user.dir: C:\

What this code does

  • user.dir holds the folder the program was started from, as an absolute path with a root.
  • marks.txt has no root, so it is relative: Java will look for it inside the working directory.

An absolute path starts at a root, such as C:\Users\Asha\marks.txt or /home/asha/marks.txt. It names the same file wherever the program runs. A relative path, such as marks.txt, has no root. Java finds it by starting from the working directory. isAbsolute() tells you which kind a Path is.

Do not try to change the working directory with System.setProperty("user.dir", ...). It does not reliably move where relative paths point.

toAbsolutePath

toAbsolutePath() returns the full path that Java will really use: the working directory with your relative path added at the end. An absolute path comes back unchanged.

Example 2 · toAbsolutePath adds the working directory

AbsoluteDemo.javaJava
import java.nio.file.Path;
public class AbsoluteDemo {    public static void main(String[] args) {        Path rel = Path.of("data", "marks.txt");        Path abs = rel.toAbsolutePath();        Path workingDir = Path.of(System.getProperty("user.dir"));
        System.out.println("rel absolute?  " + rel.isAbsolute());        System.out.println("abs absolute?  " + abs.isAbsolute());        System.out.println("abs ends with rel?          " + abs.endsWith(rel));        System.out.println("abs starts with user.dir?   " + abs.startsWith(workingDir));        System.out.println("Unchanged when already abs? " + abs.toAbsolutePath().equals(abs));
        Path up = Path.of("..", "notes.txt").toAbsolutePath();        Path secondLast = up.getName(up.getNameCount() - 2);        System.out.println("Still has '..'? " + secondLast);    }}
Output
rel absolute?  false
abs absolute?  true
abs ends with rel?          true
abs starts with user.dir?   true
Unchanged when already abs? true
Still has '..'? ..

What this code does

  • toAbsolutePath() is the working directory followed by the relative path, so the result starts with user.dir and ends with data/marks.txt.
  • It does not clean the path: ../notes.txt keeps its .. name. normalize is the method that removes it.

It does not check the disk, and it does not tidy the path: .. and . stay in it. It is the best first step when a file is not found, because it prints the exact place Java looked.

resolve and resolveSibling

resolve joins a path onto the end of another: Path.of("uploads").resolve("photo.jpg") gives uploads/photo.jpg. It adds exactly one correct separator, so you never build paths by joining strings.

Example 3 · resolve instead of string joining

ResolveDemo.javaJava
import java.nio.file.Path;
public class ResolveDemo {    public static void main(String[] args) {        String folder = "uploads";        String name = "photo.jpg";        System.out.println("String join : " + folder + name);
        Path uploads = Path.of(folder);        System.out.println("resolve     : " + uploads.resolve(name));        System.out.println("Two levels  : " + uploads.resolve("2025").resolve("fest.jpg"));
        Path absolute = Path.of("backup").toAbsolutePath();        System.out.println("Absolute argument wins? " + uploads.resolve(absolute).equals(absolute));
        Path result = Path.of("reports", "result.txt");        System.out.println("Sibling     : " + result.resolveSibling("result.bak"));    }}
Sample output (Windows; macOS and Linux print / instead of \)
String join : uploadsphoto.jpg
resolve     : uploads\photo.jpg
Two levels  : uploads\2025\fest.jpg
Absolute argument wins? true
Sibling     : reports\result.bak

What this code does

  • Joining strings forgot the separator and produced uploadsphoto.jpg. resolve always adds exactly one separator, the right one for the system.
  • Resolving an absolute path returns it unchanged. resolveSibling swaps the file name and keeps the folder, which is handy for backup or output files next to the original.

String joining goes wrong in quiet ways: "uploads" + name gives uploadsphoto.jpg, and a hand-typed \ breaks on macOS and Linux. If the argument of resolve is already absolute, resolve simply returns that argument. resolveSibling replaces the last name instead: Path.of("reports", "result.txt").resolveSibling("result.bak") gives reports/result.bak, a file in the same folder.

normalize and relativize

normalize removes the parts that go nowhere: . (this folder) and a name followed by .. (go up again). college/./cse/../ece/marks.txt becomes college/ece/marks.txt. It works on the text only and never checks the disk.

Example 4 · normalize and relativize

NormalizeDemo.javaJava
import java.nio.file.Path;
public class NormalizeDemo {    public static void main(String[] args) {        Path messy = Path.of("college", ".", "cse", "..", "ece", "marks.txt");        System.out.println("Messy      : " + messy);        System.out.println("Normalized : " + messy.normalize());        System.out.println("Leading .. : " + Path.of("..", "shared", "..", "notes.txt").normalize());
        Path from = Path.of("college", "cse", "sem1");        Path to = Path.of("college", "ece", "timetable.pdf");        Path between = from.relativize(to);        System.out.println("Relative   : " + between);        System.out.println("Back again : " + from.resolve(between).normalize());
        try {            from.relativize(to.toAbsolutePath());        } catch (IllegalArgumentException e) {            System.out.println("Relative with absolute: " + e.getClass().getSimpleName());        }    }}
Sample output (Windows; macOS and Linux print / instead of \)
Messy      : college\.\cse\..\ece\marks.txt
Normalized : college\ece\marks.txt
Leading .. : ..\notes.txt
Relative   : ..\..\ece\timetable.pdf
Back again : college\ece\timetable.pdf
Relative with absolute: IllegalArgumentException

What this code does

  • normalize drops . and cancels cse with the .. after it. The first .. in ../shared/../notes.txt has nothing before it to cancel, so it stays.
  • From college/cse/sem1, going up twice reaches college, then down into ece. Resolving that relative path from from and normalizing gives back to. Mixing a relative and an absolute path throws.

A .. at the very start has nothing to cancel, so it stays.

relativize is the opposite of resolve: from.relativize(to) gives the relative path that leads from from to to, such as ../../ece/timetable.pdf. Both paths must be relative, or both absolute; mixing them throws IllegalArgumentException.

Why a file is found in the terminal but not in the IDE

The same program can find data/marks.txt in one place and fail in another, because the working directory changed. Your code did not.

Each tool picks the working directory in its own way; the four common ones are listed after the code.

Example 5 · Same code, different working directory

WhichFolderDemo.javaJava
import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;import java.util.List;
public class WhichFolderDemo {    public static void main(String[] args) throws IOException {        Path project = Path.of("demo-project");        Path dataDir = project.resolve("data");        Path srcDir = project.resolve("src");        Files.createDirectories(dataDir);        Files.createDirectories(srcDir);        Files.writeString(dataDir.resolve("marks.txt"), "Asha,91");
        Path relative = Path.of("data", "marks.txt");        for (Path workingDir : List.of(project, srcDir)) {            Path real = workingDir.resolve(relative);            System.out.println("Started in " + workingDir.getFileName()                    + ": found = " + Files.exists(real));        }
        Files.delete(dataDir.resolve("marks.txt"));        Files.delete(dataDir);        Files.delete(srcDir);        Files.delete(project);    }}
Output
Started in demo-project: found = true
Started in src: found = false

What this code does

  • Java finds a relative path by resolving it against the working directory. The loop does the same by hand for two possible working directories, the project folder and src.
  • From the project folder, data/marks.txt exists. From src Java looks for src/data/marks.txt, which does not exist, just as when you cd src in a terminal. Files.createDirectories makes the folders; the Check, create and delete lesson covers it.
  • Terminal: the folder you are in when you type java. After cd src, the working directory is src.
  • IntelliJ IDEA: the project folder by default; see Run → Edit Configurations → Working directory.
  • VS Code (Java extension): the workspace folder by default; cwd in launch.json changes it.
  • Eclipse: the project folder; see Run Configurations → Arguments → Working directory.
When a file is not found, print path.toAbsolutePath() first. Then keep data files in one fixed place, such as the project folder, or pass the path in as a program argument.

Next step

Check your understanding

11 quick questions