Monday, February 13, 2012

Reader and Writer classes

Reader classes are similar to input streams, and writer classes are similar to output streams. Reader classes descend from the abstract Reader class, whereas the Writer classes descend from the abstract Writer class.


Both readers and writers are divided into low-level and high-level classes. Low-level classes communicate with I/O devices, and high-level classes communicate with the low-level ones.
Readers and writers are designed specifically for Unicode characters. Low-level readers and writers deal with chars.
The java.io package provides the following low-level Reader classes:
  • FileReader
  • CharArrayReader
  • PipedReader
  • StringReader
FileReader
The FileReader class is used to read streams of characters from a file.

This class is useful to read text files.
CharArrayReader
The CharArrayReader class reads arrays of characters by implementing a character buffer. The character array acts like a character input stream.
PipedReader
The PipedReader class provides a piped character-input stream.

It should be used with a piped character-output stream so that data written to the PipedWriter will be available from this reader.
StringReader
The StringReader class uses strings as its source of a character stream. Individual characters can be marked and read from the string.
The high-level reader classes include
  • BufferedReader
  • FilterReader
  • InputStreamReader
BufferedReader
The BufferedReader class is used to read text from a character-input stream.

You can use the class to improve the efficiency of your code. Buffers enable you to write and read data in bulk. It is recommended to always use buffered I/O.
FilterReader
The FilterReader class is an abstract class that is used to filter character streams. By overriding the appropriate methods of FilterReader, a subclass can decide what gets read and how it is handled. For example, you can filter lines from a file, based on a regular expression.
InputStreamReader
The InputStreamReader is a class that is used to convert a byte stream into a set of characters, using a specified Charset. You can use InputStreamReader to accept input from System.In, up to a designated escape character or sequence.
Consider the code for the InnerActionListener class. The FileReader class, which the application uses to read data, has two constructors. One constructor takes a File object as a parameter.
class InnerActionListener
  implements ActionListener {
  public void actionPerformed (ActionEvent e) {
    String s ;
    long len ;
    contents.setText(null) ;
    File f = new File (tb.getText().trim()) ;
    if (f.exists() && f.isFile()
    && f.canRead()) {
      try {
        FileReader buff = new FileReader (f) ;
        BufferedReader theFile = 
        new BufferedReader(buff) ;
        while ((s = theFile.readLine()) != null) {
          contents.append (s + "\n") 
        }
        target.setText(tb.getText().trim()+"2") ;
        theFile.close() ;
FileReader(String pathname)
FileReader(File file)
The application first creates a File object. The File object allows you to interrogate the file system.
The file object is passed into the constructor for a FileReader called buff. The FileReader is a low-level object that allows you to read from a file.
BufferedReader - one of the high-level readers in the java.io package - has an internal buffer that enables data to be read in large blocks. This reduces I/O overhead.
class InnerActionListener
  implements ActionListener {
  public void actionPerformed (ActionEvent e) {
    String s ;
    long len ;
    contents.setText(null);
    File f = new File (tb.getText().trim()) ;
    if (f.exists() && f.isFile()
    && f.canRead()) {
      try {
        FileReader buff = new FileReader (f) ;
        BufferedReader theFile = 
        new BufferedReader(buff);
        while ((s = theFile.readLine()) != null) {
          contents.append (s + "\n") ;
        }
        target.setText(tb.getText().trim()+"2") ;
        theFile.close();
Its readLine method can read the next line of text sent to it by a low-level reader.
String readLine() throws IOException
It is a good idea to wrap buffered readers around unbuffered readers to make I/O more efficient.
A BufferedReader object can accept any type of low-level reader as an input source. For example, you can specify that the buff FileReader object is used as an input source by passing it into the constructor of the BufferedReader class as a parameter.
class InnerActionListener
  implements ActionListener {
  public void actionPerformed (ActionEvent e) {
    String s ;
    long len ;
    contents.setText(null);
    File f = new File (tb.getText().trim()) ;
    if (f.exists() && f.isFile()
    && f.canRead()) {
      try {
        FileReader buff = new FileReader (f) ;
        BufferedReader theFile = 
        new BufferedReader(buff) ;
        while ((s = theFile.readLine()) != null) {
          contents.append (s + "\n") ;
        }
        target.setText(tb.getText().trim()+"2") ;
        theFile.close() ;
You can use a while loop to read the next line from the specified file and display it in the application's contents area.
As with input and output streams, most reader classes have a corresponding writer class. In this example, an application uses a FileReader and a BufferedReader to read files. It uses a FileWriter and a BufferedWriter to write them.
class innerButtonListener extends MouseAdapter{
  public void mouseClicked(MouseEvent evt) {
  File f = new File(target.getText().trim());
    Button b2;
    if(f.exists()) {
      enter.setText("This file already exists");
      return;
    }
  try{
    FileWriter output = new FileWriter(f);
    BufferedWriter out =
    new BufferedWriter(output);
    String s = contents.getText();
    //write out contents of TextArea
    out.write(s,0,s.length());
    //send output from write to file
    out.flush();
    out.close();
    //close files
    output.close();
  }
The write method of BufferedWriter writes the data from the application's contents area.
But it does not write data to its destination if the amount of data is smaller than the BufferedWriter object's buffer. If that is the case, the object stores the data instead of writing it to the file. When the buffer's size limit is reached, the object writes the contents of the object's buffer to the file.
To prevent this data being lost when you close the file, you use the flush method to send all the remaining data from the BufferedWriter object's buffer to the FileWriter object.
Exception errors often occur when executing an application that uses the input and output classes. These can be thrown by the JVM. Some important errors include
  • FileNotFoundException
  • EOFException
  • InterruptedIOException
  • ObjectStreamException
FileNotFoundException
A FileNotFoundException occurs when an attempt to locate a file at a specified path is unsuccessful.
EOFException
An EOFException occurs when the end of a file is reached unexpectedly.
InterruptedIOException
An InterruptedIOException occurs when the input or output operation is interrupted unexpectedly.
ObjectStreamException
The ObjectStreamException class is the base class for errors thrown by the ObjectStream classes.

5 comments:

Post a Comment