InputStreamReader and OutputStreamWriter Classes
In Java, InputStreamReader
and OutputStreamWriter
are bridge classes that convert byte streams to character streams and vice versa. They are essential when you need to read or write text using specific character encodings.
1. Class Hierarchy#
InputStreamReader
extendsReader
OutputStreamWriter
extendsWriter
2. InputStreamReader Class#
● Constructor#
● Example: Reading a file with InputStreamReader#
Output (If input.txt contains "Hello World"):#
Explanation:#
- Reads bytes from file, decodes them into characters using the platform’s default charset.
try-with-resources
auto-closes the stream.
● int read()
#
Reads a single character.
● int read(char[] cbuf, int offset, int length)
#
Reads characters into an array with offset and length.
Output:#
● void close()
#
Closes the stream and releases any resources. If you're using try-with-resources, this is called automatically.
Example with explicit close (Not recommended):#
Output:#
3. OutputStreamWriter Class#
● Constructor#
● void write(int c)
– Writes a single character#
Output:#
File content (output.txt
):
Explanation:
- The integer
65
is the ASCII value of character'A'
. - This method writes the corresponding character to the file.
- Since we used try-with-resources, the stream is automatically closed.
● void write(char[] cbuf, int off, int len)
– Writes characters from a char array#
Output:#
File content (output.txt
):
Explanation:
- Converts the string
"Hello Java"
to a character array. - Writes the entire array to the file using the
write(char[], off, len)
method. - Here,
off = 0
andlen = chars.length
writes the full content.
● void write(String str, int off, int len)
– Writes a substring#
Output:#
File content (output.txt
):
Explanation:
- This example writes the full string to the file.
- You can also write part of the string by changing the
offset
andlength
values.
● void flush()
– Flushes the data forcibly to the file#
Output:#
File content (output.txt
****):
Explanation:
flush()
makes sure all characters in the internal buffer are written to disk.- Useful when you want to make sure data is saved before the stream is closed or reused.
● void close()
– Closes the writer and releases resources#
Output:#
File content (output.txt
****):
Explanation:
- Explicitly closes the writer using
close()
. - With try-with-resources (as used in other examples), calling
close()
manually isn’t required—it happens automatically.
Conclusion#
In this blog, we covered InputStreamReader
and OutputStreamWriter
classes, which act as bridges between byte streams and character streams.
Next, we’ll dive into FileReader and FileWriter classes, which are designed specifically for reading and writing character files.