Reader and Writer for characters
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Reader and Writer are the character twins of InputStream and OutputStream: they read and write char values instead of bytes. They are the right tool for text, as long as you tell them which charset the file uses.
FileReader and FileWriter and their charset trap
The default charset is the character encoding Java uses when you do not name one. FileReader and FileWriter use it, so the same program can read the same file differently on two computers.
FileReader reads characters from a file, and FileWriter writes characters to a file. Inside, they read or write bytes and convert them with a charset.
Example 1 · The default charset trap
import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;import java.io.Reader;import java.io.Writer;import java.nio.charset.Charset;import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.nio.file.Path;
public class CharsetTrapDemo { static String codes(String s) { StringBuilder sb = new StringBuilder(); for (char c : s.toCharArray()) { sb.append(String.format("U+%04X ", (int) c)); } return sb.toString().trim(); }
static String readAll(Path file, Charset cs) throws IOException { StringBuilder sb = new StringBuilder(); try (Reader in = new FileReader(file.toFile(), cs)) { int c; while ((c = in.read()) != -1) { sb.append((char) c); } } return sb.toString(); }
public static void main(String[] args) throws IOException { Path dir = Files.createTempDirectory("receipt"); Path file = dir.resolve("receipt.txt"); String fee = "₹500"; // ₹500 try (Writer out = new FileWriter(file.toFile(), StandardCharsets.UTF_8)) { out.write(fee); }
String good = readAll(file, StandardCharsets.UTF_8); String bad = readAll(file, Charset.forName("windows-1252")); // an old Windows default System.out.println("Saved: " + codes(fee)); System.out.println("Read as UTF-8: " + codes(good) + " same: " + good.equals(fee)); System.out.println("Read as cp1252: " + codes(bad) + " same: " + bad.equals(fee)); Files.delete(file); Files.delete(dir); }}Saved: U+20B9 U+0035 U+0030 U+0030 Read as UTF-8: U+20B9 U+0035 U+0030 U+0030 same: true Read as cp1252: U+00E2 U+201A U+00B9 U+0035 U+0030 U+0030 same: false
What this code does
- The program prints character codes instead of the characters, so the output is the same in every console. U+20B9 is ₹; U+0035 and U+0030 are the digits 5 and 0.
- The 3 UTF-8 bytes of ₹ read with windows-1252 become 3 wrong characters, ₹. That is what
new FileReader(file)does on Java 17 on a typical English Windows laptop.
The old constructors, new FileReader(name) and new FileWriter(name), use the computer's default charset. Up to Java 17, that is often windows-1252 on an English Windows laptop and UTF-8 on macOS and Linux. Since Java 18 the default is UTF-8 everywhere. So the same program can save ₹500 correctly on one laptop and read it back as junk such as ₹500 on another. The program has no bug you can see; only the charset differs.
Charset constructors since Java 11
Since Java 11, both classes have constructors that take a Charset: new FileReader(file, StandardCharsets.UTF_8) and new FileWriter(file, StandardCharsets.UTF_8). With them, the result is the same on every computer and every Java version.
Example 2 · FileWriter and FileReader with a charset, and append mode
import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;import java.io.Reader;import java.io.Writer;import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.nio.file.Path;
public class HostelNoticeDemo { public static void main(String[] args) throws IOException { Path dir = Files.createTempDirectory("notice"); Path file = dir.resolve("notice.txt");
try (Writer out = new FileWriter(file.toFile(), StandardCharsets.UTF_8)) { out.write("Hostel notice\n"); out.write("Hostel fee: ₹2500\n"); // ₹2500 } try (Writer out = new FileWriter(file.toFile(), StandardCharsets.UTF_8, true)) { out.write("Water off 10am to 12pm\n"); }
StringBuilder text = new StringBuilder(); try (Reader in = new FileReader(file.toFile(), StandardCharsets.UTF_8)) { int c; while ((c = in.read()) != -1) { text.append((char) c); } } System.out.print(text.toString().replace("₹", "Rs ")); System.out.println("Characters: " + text.length()); System.out.println("Bytes on disk: " + Files.size(file)); Files.delete(file); Files.delete(dir); }}Hostel notice Hostel fee: Rs 2500 Water off 10am to 12pm Characters: 55 Bytes on disk: 57
What this code does
- Both writers and the reader name UTF-8, so the file reads back the same on any computer. The third line was added by the append-mode constructor.
- The file holds 55 characters but 57 bytes, because ₹ takes 3 bytes in UTF-8. The program prints
Rsin place of ₹ only so that the output shows correctly in every console.
new FileWriter(file, StandardCharsets.UTF_8, true) opens the file in append mode, adding to the end instead of emptying it. FileReader has no readLine. For line-by-line reading, wrap it in a BufferedReader, or use Files.newBufferedReader(path, UTF_8) from the Reading and Writing Text Files module, which gives you the same thing in one call.
FileReader and FileWriter you write names StandardCharsets.UTF_8.StringReader and StringWriter for testing
A StringReader is a Reader whose characters come from a String. A StringWriter is a Writer that collects everything you write into a String, which toString() returns.
Example 3 · Testing with StringReader and StringWriter
import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;import java.io.Reader;import java.io.StringReader;import java.io.StringWriter;import java.io.Writer;import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.nio.file.Path;
public class ReaderWriterTestDemo { static int countDigits(Reader in) throws IOException { int count = 0; int c; while ((c = in.read()) != -1) { if (Character.isDigit(c)) { count++; } } return count; }
static void writeReceipt(Writer out, String name, int fee) throws IOException { out.write("Receipt\n"); out.write("Name: " + name + "\n"); out.write("Fee paid: Rs " + fee + "\n"); }
public static void main(String[] args) throws IOException { System.out.println("Digits in a test string: " + countDigits(new StringReader("PNR 4521, coach B2")));
StringWriter memory = new StringWriter(); writeReceipt(memory, "Ananya", 1200); System.out.print(memory);
Path dir = Files.createTempDirectory("receipts"); Path file = dir.resolve("ananya.txt"); try (Writer out = new FileWriter(file.toFile(), StandardCharsets.UTF_8)) { writeReceipt(out, "Ananya", 1200); } try (Reader in = new FileReader(file.toFile(), StandardCharsets.UTF_8)) { System.out.println("Digits in the real file: " + countDigits(in)); } Files.delete(file); Files.delete(dir); }}Digits in a test string: 5 Receipt Name: Ananya Fee paid: Rs 1200 Digits in the real file: 4
What this code does
countDigitsandwriteReceipttake aReaderand aWriter, so the same code runs on a string in a test and on a real file in the program.StringWritercollected the receipt in memory; printing it callstoString(). No file was needed to check what the method writes.
They make testing easy. A method that takes a Reader or a Writer parameter, instead of a file name, works with a file in the real program and with a string in a quick test. You can check the result without creating, reading or deleting any file. Neither class touches the disk, so closing them does nothing; you may still use try-with-resources to keep the code uniform.
Reading into a char array
read(char[] buf) fills the array with up to buf.length characters and returns how many it read, or -1 at the end. Use only buf[0] to buf[n - 1], for example new String(buf, 0, n) or out.write(buf, 0, n).
Example 4 · read(char[]) and transferTo
import java.io.IOException;import java.io.Reader;import java.io.StringReader;import java.io.StringWriter;
public class CharArrayReadDemo { public static void main(String[] args) throws IOException { char[] buf = new char[8]; try (Reader in = new StringReader("Hostel fee paid by UPI")) { int n; while ((n = in.read(buf)) != -1) { System.out.println(n + " chars: [" + new String(buf, 0, n) + "]"); } }
StringWriter copy = new StringWriter(); try (Reader in = new StringReader("Exam on Monday")) { long moved = in.transferTo(copy); System.out.println("transferTo moved " + moved + " chars: " + copy); } }}8 chars: [Hostel f] 8 chars: [ee paid ] 6 chars: [by UPI] transferTo moved 14 chars: Exam on Monday
What this code does
- 22 characters with an 8-character buffer take three reads: 8, 8 and 6.
new String(buf, 0, n)uses only the new characters of each read. transferTo(Java 10) copied the wholeReaderinto theStringWriterin one call and returned the number of characters as along.
The single-character read() returns an int: a character code from 0 to 65535, or -1 at the end. Cast it to char only after the -1 check.
Since Java 10, reader.transferTo(writer) copies every remaining character from a Reader to a Writer and returns the count.
Next step
Check your understanding
11 quick questions