Lesson 8: IO and the Java Class Library.

Overview

Java consists of a language called Java, an machine architecture called the Java Virtual Machine, and a large collection of objects, some intrinsic to the language, some part of the Java Foundation Classes. To explore these classes yourself, refer to the official documentation at java.sun.com or the on-line help available with all IDE's, or a reference text such as O'Reilly's Java in a Nutshell and Java Foundation Classes in a Nutshell.

Java uses the stream concept for its IO: bytes or characters are accessed one at a time in the order they are typed, or are found in a file, or are sent to be printed. There is some, but limited support, for jumping backwards to retrieve bytes already "ingested", or jumping forward to peek at bytes not already reached. (Random Access Files are an exception, but the ability to modify such a file tends to be limited to appending at the end).

In Java, Input/Output is represented and accessed through objects. These classes have two kinds of superclasses, depending upon whether the stream is a byte stream or a character stream. The simplest I/O is a byte stream. These are represented by the abstract classes java.io.InputStream and java.io.OutputStream. For character streams, Java uses the Unicode character standard. Unicode is a 16 bit universal character set which includes letters and symbols from all the world's languages. These streams are represented by abstract classes java.io.Reader and java.io.Writer.

Examples:

  1. CountBytes.java
  2. YoungerThan.java
  3. More.java
  4. ReadIntegers.java
  5. ReadIntegersException.java

The details

At the foundation for raw byte I/O are the abstract classes java.io.InputStream java.io.OutputStream. For text I/O, the foundation are the abstract classes java.io.Reader and java.io.Writer. These streams are either extended to implement streams coming from or going to specific places, such as the FileReader class ( a text stream coing from a file) or filtered to add additional functionality, such as the BufferedReader class which allows a text stream to be read line by line.

Unix files are byte-oriented. The type of java.lang.System.in is InputStream. In order to read characters from System.in, it must be wrapped in a class which converts bytes to Unicode. The class InputStreamReader takes an InputStream as a constructor argument and is a subclass of Reader. Using this class, you get character input properly from System.in.

The java.io.File class is the basis for manipulating the file system.