Skip to content
C

Reader and Writer

Reader and Writer are base classes designed specifically for handling character (text) data, rather than raw bytes. They handle text encoding details more conveniently than InputStream/OutputStream.


1. What are Reader and Writer?

Reader and Writer are base classes designed specifically for handling character (text) data, rather than raw bytes. They handle text encoding details more conveniently than InputStream/OutputStream.

2. Why is it used?

When working specifically with text files, Reader and Writer classes (like FileReader and FileWriter) are simpler and more appropriate, since they're designed to correctly interpret readable characters rather than raw binary bytes.

3. Real-Life Example

Think of reading a printed letter written in your own language, versus reading a strip of Morse code that needs decoding first. Reader/Writer work directly with readable text, while InputStream/OutputStream deal with raw, undecoded data.

4. Syntax

java
Reader reader = new FileReader("file.txt"); Writer writer = new FileWriter("output.txt");

5. Example Program

java
import java.io.*; public class ReaderWriterDemo { public static void main(String[] args) throws IOException { FileWriter writer = new FileWriter("notes.txt"); writer.write("Hello, Java file handling!"); writer.close(); FileReader reader = new FileReader("notes.txt"); int character; StringBuilder content = new StringBuilder(); while ((character = reader.read()) != -1) { content.append((char) character); } reader.close(); System.out.println(content); } }

Output:

Hello, Java file handling!

6. Key Points to Remember

  • Reader/Writer are meant for character (text) data; InputStream/OutputStream are meant for raw byte data.
  • BufferedReader and BufferedWriter are commonly wrapped around these for more efficient, line-based reading and writing.
  • Always close readers and writers after use to avoid resource leaks.