Chapter 22: File I/O and Serialization

Almost every real-world Java application needs to

  • read data from files (configuration, logs, user data, CSV, JSON…)
  • write data to files (save game progress, generate reports, export data…)
  • serialize objects (save them to disk, send over network)
  • deserialize them back (read from disk, receive from network)

We will cover everything very slowly and thoroughly, step-by-step, with many complete, runnable examples.

Let’s start!

1. Classical File I/O (The traditional way – still very important)

These classes are located in package java.io

Most important classes you will use every day

Class What it does Use when you want to… Character / Byte
File Represents file or directory path Check exists, create, delete, get size…
FileReader Read characters from file Read text files character by character Character
FileWriter Write characters to file Write text files Character
BufferedReader Read text efficiently line by line Most common way to read text files Character
BufferedWriter Write text efficiently Most common way to write text files Character
FileInputStream Read raw bytes Images, videos, binary files Byte
FileOutputStream Write raw bytes Images, videos, binary files Byte

Very Important Rule (Beginners always forget this!)

Always close files after you finish using them → Otherwise → file handles leak, program may crash when too many files are open → Best practice in 2025–2026 → use try-with-resources (automatic close!)

2. Reading Files – Most Common Ways

Way 1 – Classic BufferedReader + try-with-resources (Most Recommended)

Java

Way 2 – Read all lines at once (very convenient – Java 8+)

Java

3. Writing Files – Most Common Ways

Way 1 – BufferedWriter + try-with-resources (Most Recommended)

Java

Way 2 – Write all lines at once (very clean – Java 8+)

Java

4. Modern Way – NIO.2 (java.nio.file) → Recommended in 2025–2026

NIO.2 (Non-blocking I/O) is more powerful, cleaner, and more modern

Most important classes:

Class Purpose Most used methods
Path Represents file/folder path Paths.get(“file.txt”)
Files Static utility class – almost everything readAllLines(), write(), exists(), createFile(), size()…

Very common NIO.2 patterns

Java

5. Serialization & Deserialization (Saving & Loading Objects)

Serialization = converting object → stream of bytes (save to file, send over network) Deserialization = converting bytes → object back

Important Rules:

  • Class must implement java.io.Serializable
  • All fields that should be saved must be Serializable too (or marked transient)
  • static fields are not serialized

Example – Full Serialization / Deserialization

Java

Quick Summary Table

Task Recommended Modern Way (2025–2026) Classical Way (still okay)
Read text file line by line Files.readAllLines() or Files.lines() BufferedReader + readLine()
Write text file Files.write() BufferedWriter
Append to file Files.write(…, StandardOpenOption.APPEND) new FileWriter(path, true)
Save whole object to file ObjectOutputStream + Serializable Same
Most safe & clean way Always use try-with-resources

Homework for You (Very Practical!)

  1. Basic Create a program that reads a text file line by line and prints only lines that contain word “java” (case insensitive)
  2. Medium Write a program that reads numbers from file numbers.txt (one number per line) → calculates sum, average, min, max
  3. Advanced Create a small Contact class (name, phone, email) → implement Serializable → save 5 contacts to file → read them back and print
  4. Fun Make a program that appends current timestamp + random message to a log file every time it runs
  5. Challenge Try to serialize a class that contains another object → see what happens if inner object is not Serializable

You are doing amazing! File I/O + Serialization is one of the most frequently used skills in real Java jobs.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *