Home : Course Map : Chapter 9 : Java : Supplements :
Text Character I/O
JavaTech
Course Map
Chapter 9

Introduction
Overview
Streams
Wrappers,Buffers
Console I/O
  Text Output 
     Demo 1

  Formatter/printf()
     Demo 2

  Tex 2t Input
     Demo 3

  Scanner
     
Demo 4
File Class
  File I/O
  File Output-Text
     Demo 5

  Formatter to File
     Demo 6

  File Input - Text
    Demo 7

  Scanner - Files
     Demo 8

  File I/O - Binary
     Demo 9
   Demo 10
File Chooser Dialog
  Demo 11

Character Codes
  Demo 12
   Demo13
Object I/O
Types to Bytes
Stream Filters
Other I/O Topics
Exercises

    Supplements
Character I/O
  Demo 1   Demo 2
Random Access
  Demo 3
ZIP/GZIP Streams
  Demo 4
Piped Streams
  Demo 5
NIO Framework
More NIO
  Demo 6

     About JavaTech
     Codes List
     Exercises
     Feedback
     References
     Resources
     Tips
     Topic Index
     Course Guide
     What's New

In the Chapter 9: Java section we discussed a number of classes and techniques for text I/O, particularly with respect to the console and to files. The programs there mostly deal with I/O of strings such as formatted numerical values. The two programs below show older techniques for text I/O in which text is moved one character at a time.

InputStreamReader & OutputStreamWriter

Although not really needed for simple console I/O, the InputStreamReader and OutputStreamWriter classes nicely illustrate stream wrapping concepts. The System.out and System.in use 8-bit encoded character streams. Java version 1.1 made available 16-bit streams that are compatiable with the 2-byte Unicode encoding, which is used within Java for all character representations.

To provide for 16-bit streams and other capabilities, the example below wraps the System.in stream with an InputStreamReader and the System.out stream with an OutputStreamWriter.

import java.io.*;
/**
  * Demonstrate reading characters from the console using
  * the standard input from System.in wrapped with
  * InputStreamReader.
**/
public class SingleCharIOApp
{
  public static void main (String arg[]) {
    char ch;
    int tmp = 0;

    // System.in std input stream already opened by default.
    // Wrap in a new reader stream to obtain 16 bit capability.
    InputStreamReader reader = new InputStreamReader (System.in);

    // System.out std output stream already opened by default.
    // Wrap in a new writer stream to obtain 16 bit capability.
    OutputStreamWriter writer = new OutputStreamWriter (System.out);

    try {
      // Hit CTRL-Z on PC's to send EOF, CTRL-D on Unix.
      // The EOF puts -1 = 0xFFFFFFFF into integer.
      while (tmp != -1 ) {
        // Read a single character from keyboard
        tmp  = reader.read ();

        // A 1 byte character is returned in integer.
        // Cast to char to get character in low 2 bytes.
        ch = (char) tmp;

        // If a symbol character with 2 byte unicode read in,
        // the will see 4 hex output
        writer.write ("echo " + ch
            + " whose code = "+ Integer.toString (tmp,16) + '\n');

        // Need to flush the OutputStream buffer to get the
        // characters sent to the screen.
        writer.flush ();
      }
    }
    catch (IOException e) {
        System.out.println ("IO error:" + e );
    }
  } // main
} // class SingleCharIOApp

If there is an end of file (EOF), then -1 = 0xFFFFFFFF is held by the integer, thus using all four bytes. The table below shows typical output.

Example Case
c:\> java SingleCharIO_App1
abc123+- <= user input
echo a whose code = 61
echo b whose code = 62
echo c whose code = 63
echo 1 whose code = 31
echo 2 whose code = 32
echo 3 whose code = 33
echo + whose code = 2b
echo - whose code = 2d
whose code = d
echo
whose code = a

 

The hex values shows the codes according to the default encoding for the particular host OS system on which it was run (may look different when run on your system.) For the standard ASCII characters the hex values are the same.

Note: this DOS program does line returns with "\r\n". Thus the program reads the return key hit as two more characters. The "\r" causes the cursor to move all the way to the left, which is why there is no echo seen for it above. The "\n"causes the line change.

PrintWriter

The OutputStreamWriter class only has a few basic write() methods. We can obtain many print(..) and println() overloaded methods with the PrintWriter class. (See the API Specifications for the PrintWriter class.)

So in the following example we wrap the OutputStreamWriter instance with a PrintWriter and thus obtain use of its methods. We also take advantage of the autoflushing switch in one of the PrintWriter constructors so that we do not have to flush the buffers explicitly ourselves after every print.

import java.io.*;
/**
  * Demonstrate reading characters from the console using
  * the standard input/output from System.in/System.out
  * wrapped with InputStreamReader & OutputStreamWriter, resp.
  * Here wrap PrintWriter around the OutputstreamWriter.
 **/
public class SingleCharPWApp
{
  public static void main (String arg[]) {
    char ch;
    int tmp=0;
    // System.in std input stream already opened by default.
    // Wrap in a new reader stream to obtain 16 bit capability.
    InputStreamReader reader = new InputStreamReader (System.in);

    // System.out std output stream already opened by default.
    // Wrap in a new writer stream to obtain 16 bit capability.
    OutputStreamWriter writer = new OutputStreamWriter (System.out);

    // Wrap the PrintWriter stream around this output stream
    // and use the second argument in the constructor to turn
    // on the autoflush.
    PrintWriter pw = new PrintWriter (writer,true);

    try {
      // Hit CTRL-Z on PC's to send EOF, CTRL-D on Unix.
      // The EOF puts -1 = 0xFFFFFFFF into integer.
      while  (tmp != -1) {
        // Read a single character from keyboard
        tmp  = reader.read ();

        // A 1 byte character is returned in integer.
        // Cast to char to get character in low 2 bytes.
        ch = (char) tmp;

        // PrintWriter does autoflushing and offers a println
        // method that includes line return.
        pw.println ("echo " + ch
            + " whose code = "+ Integer.toString (tmp,16));
      }
    }
    catch  (IOException e) {
        System.out.println ("IO error:" + e );
    }
  } // main

} // class SingleCharPWApp

 

This program produces similar output as the previous program.

 

References & Web Resources

 

Latest update: Nov. 10, 2004

              Tech
Histogram I/O
Hist I/O - Get/Set
  Demo 1
Hist I/O - Objects
  Demo 2
HistogramStream
  Demo 3
Filtering Data
  Demo 4
Exercises

           Physics
Physics Model
Simulation Design
Physics Simulator
  Demo 1
Experiment Design
Experiment Sim.
  Demo 2
Analysis
Expt. + Analysis
  Demo 3
Exercises

  Part I Part II Part III
Java Core 1  2  3  4  5  6  7  8  9  10  11  12 13 14 15 16 17
18 19 20
21
22 23 24
Supplements

1  2  3  4  5  6  7  8  9  10  11  12

Tech 1  2  3  4  5  6  7  8  9  10  11  12
Physics 1  2  3  4  5  6  7  8  9  10  11  12

Java is a trademark of Sun Microsystems, Inc.