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.

TaskMethod
Build a pathPath.of("data", "orders.csv")
Check existenceFiles.exists(path)
Read all textFiles.readString(path)
Read linesFiles.readAllLines(path) / Files.lines(path)
Write textFiles.writeString(path, text)
AppendFiles.writeString(path, text, StandardOpenOption.APPEND)
Copy / move / deleteFiles.copy, Files.move, Files.delete, Files.deleteIfExists
Create foldersFiles.createDirectories(path)
SizeFiles.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.