← Back to Chapters

Java Character Streams

? Java Character Streams

? Quick Overview

Character Streams in Java are used to read and write text data (characters). They are designed to handle Unicode characters and are ideal for text-based input and output.

? Key Concepts

  • Works with characters instead of bytes
  • Supports Unicode
  • Used for text files
  • Classes are found in java.io package

? Syntax / Theory

Character streams use Reader and Writer as abstract base classes. Common implementations include FileReader and FileWriter.

? Writing Characters to a File

? View Code Example
// Writing text to a file using FileWriter
import java.io.FileWriter;
import java.io.IOException;

class WriteExample {
public static void main(String[] args) throws IOException {
FileWriter fw = new FileWriter("data.txt");
fw.write("Hello Character Stream");
fw.close();
}
}

? Reading Characters from a File

? View Code Example
// Reading text from a file using FileReader
import java.io.FileReader;
import java.io.IOException;

class ReadExample {
public static void main(String[] args) throws IOException {
FileReader fr = new FileReader("data.txt");
int ch;
while((ch = fr.read()) != -1) {
System.out.print((char)ch);
}
fr.close();
}
}

? Live Output / Explanation

The first program writes text into a file. The second program reads the file character by character and prints it on the console.

? Interactive Simulator

Simulate how Java writes to a file and reads it back character by character.

? data.txt (File)

[Empty]

?️ Console Output

 

✅ Tips & Best Practices

  • Use character streams for text data only
  • Always close streams after use
  • Prefer BufferedReader for efficiency

? Try It Yourself

  • Write multiple lines into a file
  • Read data using BufferedReader
  • Modify text and rewrite to file