SCJP Study Guide:
API Contents


Printer-friendly version Printer-friendly version | Send this 
article to a friend Mail this to a friend


Previous Next vertical dots separating previous/next from contents/index/pdf Contents
XyzWs Study Guide: SCJP: FileReader and FileWriter

FileReader and FileWriter


The java.io package contains a collection of stream classes that support these algorithms for reading and writing. These classes are divided into two class hierarchies based on the data type (either characters or bytes) on which they operate.

The Reader and Writer are the abstract superclasses for character streams in java.io package. The Reader provides the API and partial implementation for readers--streams that read 16-bit characters. And the Writer provides the API and partial implementation for writers--streams that write 16-bit characters.

Remember that FileReader and FileWriter read and write 16-bit characters. However, most native file systems are based on 8-bit bytes. These streams encode the characters as they operate according to the default character-encoding scheme.

You can find out the default character-encoding by using System.getProperty("file.encoding"). To specify an encoding other than the default, you should construct an OutputStreamWriter on a FileOutputStream and specify it.

java.io.FileReader

The java.io.FileReader class, which is subclass of java.io.Reader, is used to read character file. It is used to

  • Read a single character.
  • Read characters into a portion of an array.
  • Read characters into an array. This method will block until some input is available, an I/O error occurs, or the end of the stream is reached.

The constructors of FileReader class assume that the default character encoding and the default byte-buffer size are appropriate. To specify these values yourself, construct an InputStreamReader on a FileInputStream.

FileReader is meant for reading streams of characters. For reading streams of raw bytes, consider using a FileInputStream.

The FileReader Class Constructors:

  • public FileReader(String fileName) creates a new FileReader, given the name of the file to read from. Imay throw a FileNotFoundException exception if the named file does not exist, is a directory rather than a regular file, or for some other reason cannot be opened for readingt
  • public FileReader(File file) creates a new FileReader, given the File to read from. It may throw a FileNotFoundException exception if the named file does not exist, is a directory rather than a regular file, or for some other reason cannot be opened for reading
  • public FileReader(FileDescriptor fd) creates a new FileReader, given the FileDescriptor to read from.

The FileReader Reading Methods:

  • public int read() reads a single character.The method returns the character read, as an integer in the range 0 to 65535 (0x00-0xffff), or -1 if the end of the stream has been reached. This method will block until a character is available, an I/O error occurs, or the end of the stream is reached. Subclasses that intend to support efficient single-character input should override this method. An IOException exception will be thrown if an I/O error occurs.
  • public int read(char[] cbuf) reads characters into an array.The method returns the number of characters read, or -1 if the end of the stream has been reached This method will block until some input is available, an I/O error occurs, or the end of the stream is reached. An IOException exception will be thrown if an I/O error occurs.
  • public int read(char[] cbuf, int off, int len) reads characters into a portion of an array. The method returns number of characters read, or -1 if the end of the stream has been reached.This method will block until some input is available, an I/O error occurs, or the end of the stream is reached. An IOException exception will be thrown if an I/O error occurs.

Misc Methods:

  • public long skip(long n) skips characters.The method returns number of characters actually skipped. This method will block until some characters are available, an I/O error occurs, or the end of the stream is reached. An IllegalArgumentException exception will be thrown if n is negative and an IOException exception will be thrown if an I/O error occurs.
  • public boolean ready() tests whether this stream is ready to be read. Returns true if the next read() is guaranteed not to block for input, false otherwise. Note that returning false does not guarantee that the next read will block. An IOException exception will be thrown if an I/O error occurs.
  • public void mark(int readAheadLimit) marks the present position in the stream. Subsequent calls to reset() will attempt to reposition the stream to this point. Not all character-input streams support the mark() operation. The readAheadLimit limits on the number of characters that may be read while still preserving the mark. After reading this many characters, attempting to reset the stream may fail. An IOException will be thrown if the stream does not support mark(), or if some other I/O error occurs.
  • public void reset() reset the stream. If the stream has been marked, then attempt to reposition it at the mark. If the stream has not been marked, then attempt to reset it in some way appropriate to the particular stream, for example by repositioning it to its starting point. Not all character-input streams support the reset() operation, and some support reset() without supporting mark(). An IOException exception will be thrown if the stream has not been marked, or if the mark has been invalidated, or if the stream does not support reset(), or if some other I/O error occurs
  • public void close() closes the stream. Once a stream has been closed, further read(), ready(), mark(), or reset() invocations will throw an IOException. Closing a previously-closed stream, however, has no effect. An IOException exception will be thrown if an I/O error occurs.

java.io.FileWriter

The java.io.FileWriter class, which is subclass of java.io.Writer, is used to write character file. It is used to

  • Write a single character.
  • Write a String.
  • Write a portion of an array of characters.
  • Write a portion of a String.

The constructors of FileWriter class assume that the default character encoding and the default byte-buffer size are acceptable. To specify these values yourself, construct an OutputStreamWriter on a FileOutputStream.

Whether or not a file is available or may be created depends upon the underlying platform. Some platforms, in particular, allow a file to be opened for writing by only one FileWriter (or other file-writing object) at a time. In such situations the constructors in this class will fail if the file involved is already open.

FileWriter is meant for writing streams of characters. For writing streams of raw bytes, consider using a FileOutputStream.

Construct a FileWriter object from a given File object. An IOException will be thrown if the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason:

  • public FileWriter(File file) constructs a FileWriter object given a File object.
  • public FileWriter(File file, boolean append) constructs a FileWriter object given a File object. If the second argument is true, then bytes will be written to the end of the file rather than the beginning.

Construct a FileWriter object from a given file name. An IOException will be thrown if the named file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason:

  • public FileWritef(String filename) constructs a FileWriter object given a file name.
  • public FileWriter(String filename,boolean append) constructs a FileWriter object given a file name. If the second argument is true, then bytes will be written to the end of the file rather than the beginning.

Methods for writing content to a file:

  • public void write(int c) writes a single character. The character to be written is contained in the 16 low-order bits of the given integer value; the 16 high-order bits are ignored.
  • public void write(char[] cbuf) writes an array of characters.
  • public void write(char[] cbuf, int off, int len) writes a portion of an array of characters.
  • public void write(String str) writes a string.
  • public void write(String str,int off, int len) writes a portion of a string.

For writing a portion of characters/string, the off parameter value must in the range from 0 to length() of characters or string AND also (off + len) <= length(); otherwise a StringIndexOutOfBoundsException exception will be thrown.

For all of the writing methods, an IOException exception will be thrown if an I/O error occurs .

Misc Methods:

  • public void flush() flushs the stream. If the stream has saved any characters from the various write() methods in a buffer, write them immediately to their intended destination. Then, if that destination is another character or byte stream, flush it. Thus one flush() invocation will flush all the buffers in a chain of Writers and OutputStreams.

If the intended destination of this stream is an abstraction provided by the underlying operating system, for example a file, then flushing the stream guarantees only that bytes previously written to the stream are passed to the operating system for writing; it does not guarantee that they are actually written to a physical device such as a disk drive. An IOException exception will be thrown if an I/O error occurs.

  • public void close() closes the stream, flushing it first. Once a stream has been closed, further write() or flush() invocations will cause an IOException to be thrown. Closing a previously-closed stream, however, has no effect. An IOException exception will be thrown if an I/O error occurs.

Examples

The following program uses FileReader and FileWriter to copy the contents of a file named input.txt into a file called output.txt :

import java.io.*;

public class CopyFile {

  public static void main(String[] args) throws IOException {
    try { 
      //Create a FileReader object
      File inputFile = new File("input.txt");
      FileReader in = new FileReader(inputFile);

      //Create a FileWriter object
      File outputFile = new File("output.txt");
      FileWriter out = new FileWriter(outputFile);

      //Copy contents
      int c;
      while ((c = in.read()) != -1)
           out.write(c);

      //Clear up
      in.close();
      out.close();
    } catch(IOException e) {}
    
  }
}

This program is very simple. It opens a FileReader on input.txt and opens a FileWriter on output.txt. The program reads characters from the reader as long as there's more input in the input file. When the input runs out, the program closes both the reader and the writer.

Summary

The FileReader and FileWriter provide fairly low-level mthods for reading and writing a text file. In practice, the FileReader is usually wrapped by BufferedReader and the FileWriter is usually wrapped by BufferedWriter or PrintWriter. These high-level classes provide more convenient ways to deal with data and also better performance.


Previous Next vertical dots separating previous/next from contents/index/pdf Contents

  |   |