← Back to Chapters

Java FileReader & FileWriter

? Java FileReader & FileWriter

? Quick Overview

java.io FileReader and FileWriter are character-based classes used in Java to read and write text files. They are ideal for handling plain text data such as logs, configuration files, and reports.

? Key Concepts

  • Character stream classes (not byte streams)
  • Used for reading and writing text files
  • Automatically handles character encoding
  • Works best with small to medium text files

? Syntax & Theory

  • FileReader reads characters from a file
  • FileWriter writes characters to a file
  • Both classes throw IOException
  • Always close streams after use

? Code Example

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

public class WriteExample {
public static void main(String[] args) throws IOException {
FileWriter writer = new FileWriter("data.txt");
writer.write("Hello Java FileWriter");
writer.close();
}
}
? View Code Example
// Reading text from a file using FileReader
import java.io.FileReader;
import java.io.IOException;

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

? Live Output / Explanation

The first program creates a file named data.txt and writes text into it. The second program reads the file character by character and prints the content to the console.

? Interactive Simulator

Test the concepts! Enter text below to "Write" it to a virtual data.txt file, then click "Read" to display it in the console.

Waiting for input...

? data.txt (Hard Disk)

(Empty File)

?️ Console (Output)

_

✅ Tips & Best Practices

  • Always close FileReader and FileWriter to avoid memory leaks
  • Use try-with-resources for safer file handling
  • Prefer BufferedReader and BufferedWriter for large files

? Try It Yourself

  • Write multiple lines to a file using FileWriter
  • Count characters while reading a file
  • Modify the program to append data instead of overwriting