bhylu.com

Advertisements

Java Process Text Through Buffered Readers and Writers

Character streams convert between text and bytes, while buffering reduces the number of small underlying operations. Resource closure still belongs to an explicit owner.

Understand the idea

BufferedReader.readLine returns a line without its line terminator, or null at end of input. An empty string is therefore a real empty line, not EOF. BufferedWriter.newLine writes the platform line separator, while explicit is useful when a format specifies LF. Creating readers and writers through Files lets this example name UTF-8 instead of relying on a default encoding.

Run it locally

Use a local JDK 21 or newer. Save the complete example as Main.java in a separate lab folder, then compile and run it with the commands below. Java examples do not run in Bhylu’s browser playground. The -ea option enables assertion checks used by some lessons.

JDK and terminal setup

javac --release 21 -encoding UTF-8 -d out Main.java
java -ea -cp out Main

A worked example

Java 21+ · Main.java

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.nio.file.*;
import java.nio.charset.StandardCharsets;

public class Main {
    public static void main(String[] args) throws Exception {
        Path folder = Files.createTempDirectory("bhylu-buffer-");
        Path file = folder.resolve("labels.txt");
        try {
            try (BufferedWriter writer = Files.newBufferedWriter(file, StandardCharsets.UTF_8)) {
                writer.write("Clay"); writer.newLine();
                writer.write("Wood"); writer.newLine();
            }
            try (BufferedReader reader = Files.newBufferedReader(file, StandardCharsets.UTF_8)) {
                String line;
                while ((line = reader.readLine()) != null) System.out.println(line.toUpperCase(java.util.Locale.ROOT));
            }
        } finally {
            Files.deleteIfExists(file);
            Files.delete(folder);
        }
    }
}

Expected output

CLAY
WOOD

The writer is closed before the reader is opened. Each loop iteration receives one complete line and prints a transformed result. The transformation does not rewrite the original file. For formats where line endings carry special meaning, do not assume readLine preserves the exact original separators.

Check the official Java documentation for detailed contracts and supported options.