Readers Writers  «Prev  Next»

Lesson 1

Using Java Readers and Writers

Java's Reader and Writer classes provide a powerful way to handle text I/O operations, focusing specifically on character streams rather than byte streams. Readers are used for reading text data from sources like files, network sockets, or input streams, ensuring that the data is interpreted correctly according to the character encoding specified. For example, FileReader can be used to read from a text file. To read from a file, you would typically wrap a FileReader with a BufferedReader, which allows for efficient reading of characters, arrays, or lines by buffering input from the underlying stream. This buffering significantly reduces the number of calls to the native input API, thereby improving performance. The read() method of BufferedReader can read characters one at a time or read a whole line using readLine(), which is particularly useful for text processing where line-by-line reading is needed.
On the writing side, Writers are employed to write text to destinations like files or output streams. The FileWriter class is commonly used to write text to a file, and similar to reading, it's beneficial to wrap FileWriter with a BufferedWriter for efficiency. BufferedWriter provides a method like write() to output strings or characters, and newLine() to append a line separator appropriate to the system. This setup allows for batch writing of characters to the underlying stream, reducing the system calls for writing and enhancing performance. When dealing with different character encodings, you might use classes like InputStreamReader and OutputStreamWriter, which can be initialized with a specific charset to ensure the correct encoding and decoding of characters. Both Readers and Writers support the concept of chaining, where you can stack multiple stream classes to achieve complex I/O behaviors, like compression or encryption, before the data reaches or leaves its final source or destination.
This module shows you how to perform more sophisticated reading and writing of text files. You will learn about the following:
  1. How to use readers and writers to read and write strings and character arrays
  2. How to use BufferedReaders to read text files one line at a time, and how to use BufferedWriters to efficiently output them
  3. How to write filtered readers and writers that manipulate text before passing it on

Use Readers and Writers to read and write Character Arrays in Java 1.1

In Java 1.1, you can use `CharArrayReader` and `CharArrayWriter` to read and write character arrays, respectively. These classes belong to the `java.io` package and provide efficient handling of character streams.
1. Using `CharArrayReader` to Read from a Character Array The `CharArrayReader` reads characters from a character array as if it were an input stream.
Example: Reading from a Character Array
import java.io.CharArrayReader;
import java.io.IOException;

public class CharArrayReaderExample {
    public static void main(String[] args) {
        char[] charArray = "Hello, Java 1.1!".toCharArray(); // Convert string to char array

        try (CharArrayReader reader = new CharArrayReader(charArray)) {
            int data;
            while ((data = reader.read()) != -1) { // Read character by character
                System.out.print((char) data);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Output:
Hello, Java 1.1!


2. Using `CharArrayWriter` to Write to a Character Array
The `CharArrayWriter` collects characters written to it and allows retrieval as a character array.
Example: Writing to a Character Array
import java.io.CharArrayWriter;
import java.io.IOException;

public class CharArrayWriterExample {
    public static void main(String[] args) {
        try (CharArrayWriter writer = new CharArrayWriter()) {
            writer.write("Java 1.1 Character Streams"); // Write data to the writer
            char[] writtenData = writer.toCharArray(); // Convert to character array
            
            System.out.println("Written Data: " + new String(writtenData)); // Convert char array to string and print
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Output:
Written Data: Java 1.1 Character Streams

Summary of `CharArrayReader` and `CharArrayWriter`
Class Purpose
CharArrayReader Reads characters from a character array.
CharArrayWriter Writes characters to an internal character array, which can later be retrieved.

These classes are useful for handling character streams efficiently when working with in-memory text manipulation.

Java provides two sets of classes for reading and writing. The Stream section of package java.io is for reading or writing bytes of data. Older languages tended to assume that a byte (which is a machine-specific collection of bits, usually eight bits on modern computers) is exactly the same thing as a "character", which is represented by a letter, digit, or other linguistic element.
However, Java is designed to be used interanationally, and eight bits is simply not enough to handle the many different character sets used around the world. Script-based languages like Arabic and Indian languages, and pictographic languages like Chinese, Japanese, and Korean each have many more than 256 characters, the maximum that can be represented in an eight-bit byte. The unification of these many character code sets is called Unicode. This is the most widely used standard at this time. Both Java and XML use Unicode as their character sets, allowing you to read and write text in any of these human languages. But you have to use Readers and Writers, not Streams, for textual data.

Streams, Readers and Writers

Unicode itself does not solve the entire problem. Many of these human languages were used on computers long before Unicode was invented, and they did not all pick the same representation as Unicode. In addition, there are many files encoded in a particular representation that is not Unicode. So conversion routines are needed when reading and writing to convert between Unicode String objects used inside the Java machine and the particular external representation that a user's files are written in. These converters are packaged inside a powerful set of classes called Readers and Writers. Readers/Writers are always used instead of InputStreams/OutputStreams when you want to deal with characters instead of bytes.

SEMrush Software