Skip to main content
Java Basics
CHAPTER 22 Beginner

File Handling in Java

Updated: May 17, 2026
5 min read

# CHAPTER 22

File Handling in Java

1. Introduction

Real applications work with files — reading configuration files, saving user data, generating reports, and processing logs. Java provides multiple APIs for file operations, from the classic java.io package to the modern java.nio.file package.

2. Creating and Checking Files

java
12345678
import java.io.File;

File file = new File("notes.txt");
System.out.println("Exists: " + file.exists());
System.out.println("Name: " + file.getName());
System.out.println("Path: " + file.getAbsolutePath());
System.out.println("Is File: " + file.isFile());
System.out.println("Is Directory: " + file.isDirectory());

3. Writing to Files

java
12345678910
import java.io.FileWriter;
import java.io.IOException;

try (FileWriter writer = new FileWriter("notes.txt")) {
    writer.write("Hello, Java File Handling!\n");
    writer.write("This is line 2.\n");
    System.out.println("File written successfully.");
} catch (IOException e) {
    System.out.println("Error: " + e.getMessage());
}

4. Reading Files

Using BufferedReader:
java
1234567891011
import java.io.BufferedReader;
import java.io.FileReader;

try (BufferedReader reader = new BufferedReader(new FileReader("notes.txt"))) {
    String line;
    while ((line = reader.readLine()) != null) {
        System.out.println(line);
    }
} catch (IOException e) {
    System.out.println("Error: " + e.getMessage());
}

Using java.nio.file (Modern approach):

java
12345
import java.nio.file.*;
import java.util.List;

List<String> lines = Files.readAllLines(Path.of("notes.txt"));
lines.forEach(System.out::println);

5. Appending to Files

java
123
try (FileWriter writer = new FileWriter("notes.txt", true)) { // true = append
    writer.write("This line is appended.\n");
}

6. Deleting Files

java
123456
File file = new File("temp.txt");
if (file.delete()) {
    System.out.println("Deleted: " + file.getName());
} else {
    System.out.println("Failed to delete.");
}

7. Serialization Basics

Converting an object to bytes for storage:
java
123456789101112131415161718
import java.io.*;

class Student implements Serializable {
    String name;
    int age;
    Student(String name, int age) { this.name = name; this.age = age; }
}

// Write object
try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("student.dat"))) {
    out.writeObject(new Student("Alice", 20));
}

// Read object
try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("student.dat"))) {
    Student s = (Student) in.readObject();
    System.out.println(s.name + " - " + s.age);
}

8. Mini Project: Notes Application

java
1234567891011121314151617181920212223242526272829303132333435363738
import java.io.*;
import java.util.Scanner;

public class NotesApp {
    static final String FILE = "my_notes.txt";

    public static void main(String[] args) throws IOException {
        Scanner sc = new Scanner(System.in);
        boolean running = true;

        while (running) {
            System.out.println("\n1. Add Note  2. View Notes  3. Exit");
            int choice = sc.nextInt(); sc.nextLine();

            switch (choice) {
                case 1:
                    System.out.print("Enter note: ");
                    String note = sc.nextLine();
                    try (FileWriter fw = new FileWriter(FILE, true)) {
                        fw.write(note + "\n");
                    }
                    System.out.println("Note saved!");
                    break;
                case 2:
                    try (BufferedReader br = new BufferedReader(new FileReader(FILE))) {
                        String line;
                        System.out.println("=== YOUR NOTES ===");
                        while ((line = br.readLine()) != null) System.out.println("• " + line);
                    } catch (FileNotFoundException e) {
                        System.out.println("No notes yet.");
                    }
                    break;
                case 3: running = false; break;
            }
        }
        sc.close();
    }
}

9. MCQ Quiz with Answers

Question 1

Which class writes text to files?

Question 2

BufferedReader reads files:

Question 3

new FileWriter("f.txt", true) means:

Question 4

try-with-resources automatically:

Question 5

Serializable is a:

Question 6

Files.readAllLines() is from:

Question 7

FileNotFoundException is a:

Question 8

To check if a file exists:

Question 9

ObjectOutputStream is used for:

Question 10

file.delete() returns:

10. Summary

Java provides FileWriter/BufferedWriter for writing and FileReader/BufferedReader for reading files. The modern java.nio.file API offers cleaner alternatives. Always use try-with-resources to prevent resource leaks. Serialization converts objects to bytes for persistent storage.

11. Next Chapter Recommendation

In Chapter 23: Multithreading in Java, we'll learn how to run multiple tasks simultaneously.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·