Careeroza
Paths and Files
The Modern File API
java.nio.file (Java 7+) is the modern way to work with files. A Path describes a location; the Files class has static methods that do the work.
| Task | Method |
|---|---|
| Build a path | Path.of("data", "orders.csv") |
| Check existence | Files.exists(path) |
| Read all text | Files.readString(path) |
| Read lines | Files.readAllLines(path) / Files.lines(path) |
| Write text | Files.writeString(path, text) |
| Append | Files.writeString(path, text, StandardOpenOption.APPEND) |
| Copy / move / delete | Files.copy, Files.move, Files.delete, Files.deleteIfExists |
| Create folders | Files.createDirectories(path) |
| Size | Files.size(path) |
Note: Almost every Files method throws the checked IOException, so you must catch it or declare throws IOException.
Working with Path
Example
A Path is only a description; creating one does not touch the disk.
import java.nio.file.Path;
public class Main {
public static void main(String[] args) {
Path p = Path.of("reports", "2024", "sales.csv");
System.out.println("Path : " + p.toString().replace('\\', '/'));
System.out.println("File name : " + p.getFileName());
System.out.println("Parent : " + p.getParent().toString().replace('\\', '/'));
System.out.println("Parts : " + p.getNameCount());
System.out.println("Absolute? : " + p.isAbsolute());
Path sibling = p.resolveSibling("returns.csv");
System.out.println("Sibling : " + sibling.getFileName());
Path messy = Path.of("reports/./2024/../2024/sales.csv").normalize();
System.out.println("Normalized: " + messy.toString().replace('\\', '/'));
System.out.println("CSV file? : " + p.getFileName().toString().endsWith(".csv"));
}
}Output
Path : reports/2024/sales.csv File name : sales.csv Parent : reports/2024 Parts : 3 Absolute? : false Sibling : returns.csv Normalized: reports/2024/sales.csv CSV file? : true
Tip: Never build paths by concatenating strings with "/" or "\". Path.of and resolve use the right separator for Windows, Linux and macOS.