Java Reader and Writer Classes in Java
In Java, when working with text-based input and output (character streams), the core classes to use are Reader and Writer. These are abstract classes provided in the java.io package that form the foundation for all character-based input and output operations.
Class Hierarchy Diagram#
1. What Are Reader and Writer Classes?#
Reader: Abstract class for reading character streams.Writer: Abstract class for writing character streams.
They are used when working with text data, unlike InputStream and OutputStream which work with binary data.
2. Reader Class Methods (With Examples)#
int read()#
Reads a single character. Returns -1 at the end of the stream.
Output:#
Explanation: StringReader is used here to simulate a stream. It reads characters one by one.
int read(char[] cbuf)#
Reads characters into an array and returns the number of characters read.
Output:#
void close()#
Closes the reader and releases any associated system resources.
Output:#
3. Writer Class Methods (With Examples)#
void write(int c)#
Writes a single character.
Output:#
(File output1.txt contains: A)
void write(char[] cbuf)#
Writes an array of characters.
Output:#
(File output2.txt contains: Java)
void write(String str)#
Writes an entire string.
Output:#
(File output3.txt contains: Java Writer Example)
void flush()#
Flushes the writer, forcing any buffered output to be written.
Output:#
void close()#
Closes the stream and releases system resources.
Output:#
4. When to Use Reader and Writer Classes?#
- Use Reader when you want to read text data character by character or in chunks.
- Use Writer when writing character data to a file, memory, or other output destinations.
- For raw byte data like images or audio, prefer
InputStreamandOutputStream.
Conclusion#
In this blog, we learned about the Reader and Writer classes, the foundation of Java's character-based I/O system. We explored important methods such as read, write, flush, and close with clear examples, outputs, and practical usage. These classes pave the way for more advanced classes like BufferedReader, FileReader, PrintWriter, etc., which we’ll cover in upcoming blogs.