Readers Writers  «Prev  Next»


Lesson 1

Using Java Readers and Writers

Module introduction


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

Question: How do I use readers and writers to read and write character arrays in Java 1.1?
The Reader and Writer classes in Java are abstract classes for reading and writing from and to character streams. The java.io package includes several concrete implementations of these classes that allow you to work with various input and output sources, such as files, strings, and arrays.
To read and write character arrays in Java 1.1, you may use CharArrayReader and CharArrayWriter classes respectively.
Reading a character array using CharArrayReader:
import java.io.CharArrayReader;
import java.io.IOException;

public class Main {
 public static void main(String[] args) {
  char[] charArray = {'J', 'a', 'v', 'a', ' ', '1', '.', '1'};
  CharArrayReader reader = null;
  try {
   reader = new CharArrayReader(charArray);
   int k;
    while ((k = reader.read()) != -1) {
     System.out.print((char) k);
    }
   } 
   catch (IOException e) {
    e.printStackTrace();
   } 
   finally {
    if (reader != null) {
     try {
      reader.close();
     } 
	 catch (IOException e) {
      e.printStackTrace();
     }
    }
   }
  }
}

In the above code:
  1. CharArrayReader is initialized with a character array.
  2. read() method is used in a loop to read the characters until the end of the array.
  3. Each character is cast back to a char and printed to the console.
  4. close() method is called to close the CharArrayReader instance.


Writing to a character array using CharArrayWriter:

import java.io.CharArrayWriter;
import java.io.IOException;

public class Main {
 public static void main(String[] args) {
  char[] charArray = {'J', 'a', 'v', 'a', ' ', '1', '.', '1'};
  CharArrayWriter writer = new CharArrayWriter();
   try {
    writer.write(charArray);
    System.out.println(writer.toString());
   } // end try
   finally {
     writer.close();
   }
  }
}

In the above code:
An instance of CharArrayWriter is created.
  1. write() method is called with the character array as argument.
  2. The toString() method is then called on the writer instance to convert the written characters into a string and print to the console.
  3. Finally, close() method is called to close the CharArrayWriter instance.

Keep in mind, handling of exceptions and resources is of utmost importance while dealing with I/O operations. The finally block is used to ensure that the reader or writer is closed even if an exception occurs. This is crucial to prevent resource leaks. In newer versions of Java (Java 7 and onwards), you can use the try-with-resources statement for automatic resource management.
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.