Google
 

 

up previous next contents
Up: 3. Day 3: Standard Previous: 3.1 Objectives Next: 3.3 Java networking   Contents

3.2 IO: Streams and readers

  • The java.io package provides a rich framework and class library for reading and writing any type of data (text, numbers, images) in streams from any type of location (disk, network, memory).
  • The package provides 2 class hierarchies: one for byte streams, the other for character streams.
  • Base classes for reading data: InputStream for byte streams, Reader for character streams.
  • Base classes for writing data: OutputStream for byte streams, Writer for character streams.
  • Example of copying one file to another.

      Reader in = new FileReader("one.txt");
      Writer out = new FileWriter("two.txt");
      int token = -1;
       
      while( (token != in.read()) != -1 )
      {
        out.write(token);
      }
      out.close();
    

  • The library uses the decorator pattern to add flexible stream handling. By chaining constructors of various classes, you can change how streams are read or written. Examples:
    1. We need to read some data on disk, and for performance reasons the read operation should be buffered.

        Reader bufferedFileIn = 
            new BufferedReader(new FileReader("datafile"));
      

    2. Read an in-memory byte array as UTF-8 encoded characters.

        byte[] data = ...;
        Reader charReader = 
            new BufferedReader(
              new InputStreamReader(
                new ByteArrayInputStream(data), "UTF-8"));