0% found this document useful (0 votes)
6 views3 pages

Java Reader and Writer Classes Guide

The document discusses different Java classes used for reading and writing character streams like Reader, InputStreamReader, FileReader, BufferedReader, Writer, OutputStreamWriter, FileWriter and BufferedWriter. It explains their relationships and how to use them along with character encoding and reading/writing files as examples.

Uploaded by

manjeshsingh0245
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views3 pages

Java Reader and Writer Classes Guide

The document discusses different Java classes used for reading and writing character streams like Reader, InputStreamReader, FileReader, BufferedReader, Writer, OutputStreamWriter, FileWriter and BufferedWriter. It explains their relationships and how to use them along with character encoding and reading/writing files as examples.

Uploaded by

manjeshsingh0245
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1.

Reader, InputStreamReader, FileReader and


BufferedReader
Readeris the abstract class for reading character streams. It implements the following
fundamental methods:

 read(): reads a single character.


 read(char[]): reads an array of characters.
 skip(long): skips some characters.
 close(): closes the stream.

InputStreamReader is a bridge from byte streams to character streams. It converts bytes into
characters using a specified charset. The charset can be default character encoding of the
operating system, or can be specified explicitly when creating an InputStreamReader.
FileReader is a convenient class for reading text files using the default character encoding of
the operating system.
BufferedReader reads text from a character stream with efficiency (characters are buffered to
avoid frequently reading from the underlying stream) and provides a convenient method for
reading a line of text readLine().
The following diagram show relationship of these reader classes in the [Link] package:

2. Writer, OutputStreamWriter, FileWriter and BufferedWriter

writeris the abstract class for writing character streams. It implements the following
fundamental methods:

 write(int): writes a single character.


 write(char[]): writes an array of characters.
 write(String): writes a string.
 close(): closes the stream.

OutputStreamWriter is a bridge from byte streams to character streams. Characters are encoded
into bytes using a specified charset. The charset can be default character encoding of the operating
system, or can be specified explicitly when creating an OutputStreamWriter.
FileWriter is a convenient class for writing text files using the default character encoding of the
operating system.
BufferedWriter writes text to a character stream with efficiency (characters, arrays and strings are
buffered to avoid frequently writing to the underlying stream) and provides a convenient method for
writing a line separator: newLine().

3. Character Encoding and Charset


When constructing a reader or writer object, the default character encoding of the operating system
is used (e.g. Cp1252 on Windows):
1 FileReader reader = new FileReader("[Link]");
2 FileWriter writer = new FileWriter("[Link]");
So if we want to use a specific charset, use
an InputStreamReader or OutputStreamWriter instead. For example:
1 InputStreamReader reader = new InputStreamReader(
2 new FileInputStream("[Link]"), "UTF-16");

That creates a new reader with the Unicode character encoding UTF-16.
And the following statement constructs a writer with the UTF-8 encoding:
1 OutputStreamWriter writer = new OutputStreamWriter(
2 new FileOutputStream("[Link]"), "UTF-8");

In case we want to use a BufferedReader, just wrap the InputStreamReader inside, for example:
1 InputStreamReader reader = new InputStreamReader(
2 new FileInputStream("[Link]"), "UTF-16");
3
4 BufferedReader bufReader = new BufferedReader(reader);

And for a BufferedWriter example:


1 OutputStreamWriter writer = new OutputStreamWriter(
2 new FileOutputStream("[Link]"), "UTF-8");
3
4 BufferedWriter bufWriter = new BufferedWriter(writer);

The following small program reads every single character from the
file [Link] and prints all the characters to the output console:
import [Link];
import [Link];

/**
* This program demonstrates how to read characters from a text file.
*/
public class TextFileReadingExample1 {

public static void main(String[] args) {


try {
FileReader reader = new FileReader("[Link]");
int character;

while ((character = [Link]()) != -1) {


[Link]((char) character);
}
[Link]();

} catch (IOException e) {
[Link]();
}
}
}

In the following example, a FileWriter is used to write two words


“Hello World” and “Good Bye!” to a file named [Link]:
import [Link];
import [Link];

/**
* This program demonstrates how to write characters to a text file.
*
*/
public class TextFileWritingExample1 {

public static void main(String[] args) {


try {
FileWriter writer = new FileWriter("[Link]", true);
[Link]("Hello World");
[Link]("\r\n"); // write new line
[Link]("Good Bye!");
[Link]();
}
catch (IOException e) {
[Link]();
}

Common questions

Powered by AI

FileReader is implemented for reading text files using the default system encoding, whereas InputStreamReader allows specifying a charset for conversion. BufferedReader enhances both by providing efficient reading and convenient methods like readLine(), typically wrapping an InputStreamReader to buffer input and extend functionality .

BufferedWriter improves efficiency by buffering character, array, and string output in memory, reducing the number of direct write calls to the underlying file stream. This reduces overhead and optimizes file I/O operations by consolidating write operations .

Not closing the FileReader can lead to resource leaks by leaving file handles open, potentially exhausting system resources, which might cause the program to run out of file descriptors over time and subsequent read or write operations to fail .

BufferedReader provides more efficient reading than FileReader by buffering input, which minimizes the number of read operations needed on the underlying I/O source. It also offers additional methods like readLine(), making it easier to read lines at a time .

Character-based streams, such as Reader and Writer classes, provide inherent support for character encoding conversion, crucial for correctly processing textual data across different systems and locales, whereas byte-based streams require explicit handling of encoding and decoding processes .

Using a specific charset with an InputStreamReader is preferable when the byte data being read are encoded in a character set that differs from the system's default. This ensures the data is interpreted correctly, preventing misinterpretation due to encoding mismatches .

Considerations include the encoding of the file data and system compatibility. Explicitly specifying a charset ensures consistent interpretation of characters, vital when data might not share the system's default encoding, preventing data corruption and loss of fidelity .

Using FileWriter in append mode enables existing content in a file to be preserved while new data is appended to the end. This eliminates the risk of overwriting existing data, which is crucial in data logging and scenarios where accumulated data is continuously recorded .

The Java I/O class hierarchy separates concerns by distinctively handling the conversion between byte streams and character streams through InputStreamReader and OutputStreamWriter, while abstract classes like Reader and Writer focus on character data manipulation operational logic without dictating conversion details .

InputStreamReader and OutputStreamWriter both serve as bridges between byte streams and character streams. InputStreamReader converts a byte stream into a character stream by decoding byte data into character data using a specified character set. In contrast, OutputStreamWriter converts a character stream into a byte stream by encoding character data into byte data using a specified character set .

You might also like