Path and Paths in Java: Working with File Locations
Before reading, copying or deleting a file with NIO.2, you need a Path: an object that describes where the file is. Path replaces the old File class for this job and adds powerful methods for combining and comparing locations.
This tutorial explains Path and the older Paths helper class, the parts of a path, the most useful methods and two examples.
1. What Are Path and Paths in Java?
java.nio.file.Pathis an interface (Java 7) that represents a location in a file system. Path objects are immutable and safe to share between threads. Creating one does not touch the disk.java.nio.file.Pathsis a small utility class (Java 7) whoseget()methods create paths. Since Java 11,Path.of()does the same, and thePathsdocumentation recommendsPath.of()becausePathsmay be deprecated in a future release.
2. Anatomy of a Path
Swipe sideways to see the whole diagram.
3. Creating a Path
| Code | Result |
|---|---|
Path.of("notes.txt") | A relative path, resolved against the current folder. |
Path.of("data", "2026", "sales.csv") | Joins names with the platform separator (Java 11). |
Paths.get("data", "sales.csv") | The same result through the older factory. |
file.toPath() | Converts a java.io.File. |
4. Commonly Used Path Methods
| Method | Description |
|---|---|
getFileName() / getParent() / getRoot() | Last element, everything before it, and the root (or null). |
getNameCount() / getName(int) | Number of elements and the element at an index. |
resolve(String other) | Appends other to this path. |
resolve(String first, String... more) | Appends several elements at once (Java 22). |
resolveSibling(String other) | Replaces the file name, staying in the same folder. |
relativize(Path other) | The relative path from this path to other. |
normalize() | Removes redundant . and .. elements. |
toAbsolutePath() / toRealPath() | Full path; real path with links resolved (checks the disk). |
startsWith() / endsWith() | Compare whole path elements, not characters. |
toFile() | Converts to a java.io.File. |
5. Example: Exploring and Combining Paths
A build tool works with project paths. None of these operations touches the disk; they only manipulate path names.
import java.nio.file.Path;
public class PathOperations {
public static void main(String[] args) {
Path source = Path.of("projects", "shop", "src", "Main.java"); // Java 11
System.out.println("Path: " + source);
System.out.println("File name: " + source.getFileName());
System.out.println("Parent: " + source.getParent());
System.out.println("Name count: " + source.getNameCount());
System.out.println("Absolute? " + source.isAbsolute());
Path messy = Path.of("projects", "shop", ".", "docs", "..", "src");
System.out.println("Normalized: " + messy.normalize());
Path base = Path.of("projects", "shop");
System.out.println("Resolved: " + base.resolve("test").resolve("CartTest.java"));
System.out.println("Resolved 22: " + base.resolve("test", "CartTest.java")); // Java 22
System.out.println("Relative: " + base.relativize(source));
}
}
Output
Path: projects/shop/src/Main.java File name: Main.java Parent: projects/shop/src Name count: 4 Absolute? false Normalized: projects/shop/src Resolved: projects/shop/test/CartTest.java Resolved 22: projects/shop/test/CartTest.java Relative: src/Main.java
How the code works
Path.of()joins four names;getFileName(),getParent()andgetNameCount()inspect the result.normalize()removes.and thedocs/..pair, leavingprojects/shop/src.resolve()appends names; the two-argumentresolve()(Java 22) does it in one call.relativize()finds the path fromprojects/shopto the source file.- The output uses
/; on Windows, the same program prints\.
6. Example: Building Backup File Names
A document system creates a backup name next to each file, such as invoice-118-backup.pdf.
import java.nio.file.Path;
import java.nio.file.Paths;
public class BackupNames {
static Path backupOf(Path file) {
String name = file.getFileName().toString();
int dot = name.lastIndexOf('.');
String base = (dot > 0) ? name.substring(0, dot) : name;
String ext = (dot > 0) ? name.substring(dot) : "";
return file.resolveSibling(base + "-backup" + ext); // same folder, new name
}
public static void main(String[] args) {
Path invoice = Path.of("billing", "2026", "invoice-118.pdf");
Path notes = Paths.get("billing", "README"); // older factory, same result type
System.out.println(invoice + " -> " + backupOf(invoice));
System.out.println(notes + " -> " + backupOf(notes));
System.out.println("Same path either way: " + Paths.get("billing", "README").equals(Path.of("billing", "README")));
System.out.println("Ends with README: " + notes.endsWith("README"));
}
}
Output
billing/2026/invoice-118.pdf -> billing/2026/invoice-118-backup.pdf billing/README -> billing/README-backup Same path either way: true Ends with README: true
How the code works
getFileName()isolates the name, which is split at the last dot.resolveSibling()keeps the folder and replaces only the file name.Paths.get()andPath.of()produce equal paths.endsWith("README")compares whole name elements.
7. Common Mistakes and Best Practices
- Building paths with string concatenation. Use
Path.of()orresolve()so separators are correct. - Expecting a
Pathto check the disk. UseFiles.exists()and otherFilesmethods. - Using
endsWith(".txt")to check an extension. It compares path elements; usegetFileName().toString().endsWith(".txt"). - Using
Paths.get()in new code. PreferPath.of().
8. Java Version Improvements and Java 25 Updates
| Java version | Change |
|---|---|
| Java 7 | Path and Paths introduced with NIO.2. |
| Java 11 | Path.of() factory methods. |
| Java 22 | resolve(first, more...) for appending several elements at once. |
| Java 25 | All of the above are standard. |
9. Summary
Pathdescribes a file-system location; it is immutable and does not touch the disk.- Create paths with
Path.of();Paths.get()is the older equivalent. resolve(),resolveSibling(),relativize()andnormalize()combine and clean paths.- Use the
Filesclass to work with the actual files.
Related Tutorials
10. Official Java Documentation References
Was this tutorial helpful?