VisualStudioTutor.com Java Tutorial All Lessons

Lesson 19 of 20

File Handling

Read, write, append, and organise text data using Java's modern file APIs.

Learning objectives

  • Represent file locations with Path.
  • Write and read text files with Files.
  • Append text without overwriting existing content.
  • Handle IOException.
  • Build a small persistent notes application.

1. Path and Files

The java.nio.file package provides modern file APIs. Path represents a location; Files provides operations such as read, write, copy, and create-directory.

Example: write a text file

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class WriteFile {
    public static void main(String[] args) {
        Path file = Path.of("message.txt");

        try {
            Files.writeString(file, "Hello from Java!
");
            System.out.println("File written.");
        } catch (IOException e) {
            System.out.println("Write failed: " + e.getMessage());
        }
    }
}

2. Read a text file

Path file = Path.of("message.txt");

try {
    String content = Files.readString(file);
    System.out.println(content);
} catch (IOException e) {
    System.out.println("Read failed: " + e.getMessage());
}

3. Append instead of overwrite

import java.nio.file.StandardOpenOption;

Files.writeString(
    Path.of("log.txt"),
    "Application started
",
    StandardOpenOption.CREATE,
    StandardOpenOption.APPEND
);

CREATE creates the file if necessary. APPEND adds text at the end instead of replacing the existing file.

4. Working with multiple lines

import java.util.List;

List<String> students = List.of(
    "S001,Amina,82",
    "S002,Daniel,74",
    "S003,Mei,91"
);

Files.write(Path.of("students.csv"), students);

Mini project: persistent notes

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.Scanner;

public class NotesApp {
    public static void main(String[] args) {
        Path notesFile = Path.of("notes.txt");

        try (Scanner input = new Scanner(System.in)) {
            System.out.print("Enter a note: ");
            String note = input.nextLine();

            Files.writeString(
                notesFile,
                note + System.lineSeparator(),
                StandardOpenOption.CREATE,
                StandardOpenOption.APPEND
            );

            System.out.println("
All notes:");
            System.out.println(Files.readString(notesFile));

        } catch (IOException e) {
            System.out.println("File error: " + e.getMessage());
        }
    }
}

Common mistakes

ProblemWhy it happensHow to fix it
File appears in an unexpected folderRelative paths use the program's current working directory.Print Path.of(".").toAbsolutePath() when debugging.
Existing content disappearsA write operation replaced the file.Use StandardOpenOption.APPEND when appending is intended.
Unhandled IOExceptionMany file operations can fail.Use try/catch or declare/propagate the exception appropriately.

Summary

You can now persist information beyond one program run. Lesson 20 introduces collections and generics, which are more flexible than fixed-size arrays for many real applications.