File Paths &
Working Directory
Master how Java programs locate and access files using absolute paths, relative paths, and the working directory concept.
What Is a File Path?
A file path is a string that tells the operating system (and your Java program) where a file lives on disk. Think of it as the address of a file: just as a street address leads you to a house, a file path leads your program to the right file.
The File System as a Tree
Why Paths Matter in Java
Absolute vs Relative Paths
/Users/alex/projects/data.txt
C:\Users\alex\projects\data.txt
data.txt
../config/settings.txt
The Working Directory
The working directory (also called the current directory) is the folder from which your Java program was launched. It is the starting point for resolving every relative path.
How Java Resolves Paths
Absolute vs Relative: Side by Side
| Absolute Path | Relative Path | |
|---|---|---|
| Starts from | File system root (/ or C:\) | Working directory |
| Portability | Machine-specific | Portable across machines |
| Breaks when | User name or install path changes | Working directory changes |
| Best for | System configs, temp files | Project data files |
| Java check | path.isAbsolute() == true | path.isAbsolute() == false |
Step-by-Step Path Strategy
Example 1: Simple Relative Path
Example 2: File in a Subdirectory
Example 3: Going Up with ..
Modern Java: Path & Paths
Java's java.nio.file package offers a cleaner API than the old java.io.File class. The Path interface and Paths utility provide better path manipulation and OS independence.
IDE vs Command Line
Cross-Platform Path Safety
Common Mistakes
Summary of Key Concepts
| Concept | Description | Java Example |
|---|---|---|
| Absolute Path | Full path from root | /home/user/data.txt |
| Relative Path | Path from working dir | data/input.csv |
| Working Dir | Where program launched | System.getProperty("user.dir") |
| Parent Ref (..) | Go up one directory | ../config/app.cfg |
| Current Ref (.) | Current directory (explicit) | ./data.txt |
| Paths.get() | OS-safe path creation | Paths.get("data","f.txt") |
Question 1 of 5
Which of the following is an absolute path?
Question 2 of 5
A Java program is run from /home/user/project. What absolute path does "data/report.txt" resolve to?
Question 3 of 5
What does the .. symbol mean in a file path?
Question 4 of 5
Which Java method returns the current working directory as a String?
Question 5 of 5
Your code works in IntelliJ but throws FileNotFoundException when run from the terminal. What is the most likely cause?