📘 What is a Path?
A path is simply the location of a file or directory in the file system.
📌 Absolute Path
✅ Definition:
An absolute path is the complete path from the root of the file system to the file/directory.
🧭 Examples:
OS | Absolute Path Example |
---|---|
Windows | C:\Users\Stanley\Documents\report.txt |
Unix/Linux/macOS | /home/stanley/Documents/report.txt |
✅ Always points to the same location, no matter where your program is running.
In Java:
File file = new File("C:\\Users\\Stanley\\Documents\\report.txt");
System.out.println(file.isAbsolute()); // true
📌 Relative Path
✅ Definition:
A relative path points to a file relative to the current working directory (a.k.a. project root or user.dir
).
📁 Example:
If your program is running in:
C:\Users\Stanley\MyApp\
And you access:
File file = new File("data/report.txt");
The path resolves to:
C:\Users\Stanley\MyApp\data\report.txt
✅ Relative paths are flexible and useful for projects that move between systems or environments.
🧪 In Java
File relative = new File("docs/readme.txt");
System.out.println(relative.isAbsolute()); // false
File absolute = relative.getAbsoluteFile(); // Converts to absolute
System.out.println(absolute.getPath());
You can get the current working directory like this:
System.out.println(System.getProperty("user.dir"));
🧵 TL;DR
Type | Points To | Starts From | Stable Across Systems? | Java Method |
---|---|---|---|---|
Absolute | Exact location | Root (/ or drive) | ✅ Yes | file.isAbsolute() |
Relative | Depends on current dir | user.dir | ❌ Depends on context | file.getAbsolutePath() to convert |