Files and Paths

Core Java · lesson 35 of 42 · 4 min read

Build file names with Path, then read them with the modern java.nio.file API.

Open this lesson in the learning hub

Key points

  • Path.of("/srv", "app") builds a name. It never touches the disk and the file need not exist.
  • resolve appends, getParent walks up, and normalize removes .. segments.
  • relativize is the inverse of resolve: it answers "how do I get from here to there".
  • Files is the part that does I/O: readString, readAllLines, exists.
  • For a large file use Files.lines(path) inside try-with-resources so the handle is released.
  • readLine() returns null at the end — never an empty string, which is a real blank line.

Example

import java.io.BufferedReader;
import java.io.StringReader;
import java.nio.file.Path;

public class Main {
    public static void main(String[] args) throws Exception {
        Path base = Path.of("/srv", "app");
        Path log = base.resolve("logs/today.log");

        System.out.println("base        : " + base);
        System.out.println("resolve     : " + log);
        System.out.println("fileName    : " + log.getFileName() + ", parent " + log.getParent());
        System.out.println("normalize   : " + Path.of("/srv/app/../data/./x.csv").normalize());
        System.out.println("relativize  : " + base.relativize(log));
        System.out.println("nameCount   : " + log.getNameCount() + " segments");
        System.out.println("building a Path never touched the disk");

        // Files.readAllLines(path) would do this from disk; a StringReader keeps the demo offline.
        String csv = "id,name\n1,Ada\n2,Linus\n";
        int rows = 0;
        try (BufferedReader in = new BufferedReader(new StringReader(csv))) {
            System.out.println("header: " + in.readLine());
            String line;
            while ((line = in.readLine()) != null) {
                rows++;
                System.out.println("row " + rows + ": " + String.join(" | ", line.split(",")));
            }
        }
        System.out.println("read " + rows + " rows; readLine returned null to end the loop");
    }
}

Path is text you can manipulate offline; Files is the part that hits the disk.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Core Java course, and every lesson in it is listed on the Core Java contents page.