Java · Core APIs

File I/O

Reading and writing files is a daily task — logs, CSV imports, reports. Modern Java makes it short and safe.

Intermediate 5 min Lesson 23 of 31Examples target Java 21 LTS (they also run on Java 25).
0/31 in Java
On this page · 5 min · Intermediate

In simple words#

Path is the address of a file; Files is the postman who reads letters from that address or delivers new ones.

Path
A file or folder location.
Files
Utility class: read, write, copy, delete.
Files.lines
Stream lines lazily for big files.

Learning objectives#

  • Create paths
  • Read and write text files
  • Process large files line by line
  • Handle I/O errors

Explanation#

Path.of("data", "orders.csv") builds a path portable across operating systems.

Files.readString / Files.writeString for small files; Files.readAllLines for a list of lines.

Files.lines(path) returns a stream — use try-with-resources so the file closes; good for large files.

Files.createDirectories, exists, copy, move and delete manage files. All throw IOException.

Code example: Import a CSV and write a summary#

JavaImport a CSV and write a summary Illustrative
import java.io.IOException;
import java.nio.file.*;
import java.util.stream.Stream;


public class CsvReport {
    public static void main(String[] args) throws IOException {
        Path dir = Path.of("data");
        Files.createDirectories(dir);
        Path csv = dir.resolve("orders.csv");
        Files.writeString(csv, """
            id,city,amount
            1,Pune,55000
            2,Delhi,1400
            3,Pune,2200
            """);


        double puneTotal;
        try (Stream<String> lines = Files.lines(csv)) {
            puneTotal = lines.skip(1)
                .map(line -> line.split(","))
                .filter(cols -> cols[1].equals("Pune"))
                .mapToDouble(cols -> Double.parseDouble(cols[2]))
                .sum();
        }


        Files.writeString(dir.resolve("summary.txt"), "Pune total: " + puneTotal + System.lineSeparator());
        System.out.println(Files.readString(dir.resolve("summary.txt")).strip());
    }
}
Expected output
Pune total: 57200.0

This example is illustrative. Copy or download it and run it in your own environment; the expected output is shown above.

Step-by-step explanation#

  1. createDirectories makes the folder if missing.
  2. A text block writes the sample CSV.
  3. Files.lines streams rows; skip(1) drops the header.
  4. The summary is written and read back.

Real-world use case#

Nightly jobs import CSV price lists from suppliers and write summary reports for managers.

Common mistakes#

Not closing Files.lines

Leaks file handles. Always use try-with-resources.

Naive CSV splitting

split(",") breaks on quoted commas. Use a CSV library for real data.

Best practices#

  • java.nio.file over old java.io.File
  • Stream large files
  • Specify charset when needed (UTF-8 default since Java 18)
  • Handle IOException clearly

Remember this#

Path.of(...) + Files.*.

Small → readString; big → Files.lines.

try-with-resources for streams.

Practice exercise#

Your task: Append a line to log.txt, creating the file if needed.

Show solution
Java Illustrative
Files.writeString(Path.of("log.txt"), "Started\n", StandardOpenOption.CREATE, StandardOpenOption.APPEND);

Mini quiz#

File I/O quizMultiple choice Question 1 of 1

Which method lazily streams lines from a large file?

Score so far: 0/0

Want more? Practise all Java MCQs · Java interview questions

My notes#

Saved in this browser.

Progress is saved in this browser. Sign in to sync.