JMU
Character Input and Output in Java
Intermediate Topics


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu


Background
Motivation
Some Classes for Character-Based Output
images/writers_java.gif
Some Classes for Character-Based Input
images/readers_java.gif
One Way to Use Readers
  1. Get an InputStream java.io.InputStream
    • System.in
    • From a File java.io.File (by constructing a FileInputStream java.io.FileInputStream )
    • From a URL java.net.URL (using the openStream method)
    • From a Socket java.net.Socket (using the getInputStream method)
  2. Create an InputStreamReader java.io.InputStreamReader (from the InputStream java.io.InputStream )
  3. Create a BufferedReader java.io.BufferedReader (from the InputStreamReader java.io.InputStreamReader )
One Way to Use Writers
  1. Get an OutputStream java.io.OutputStream
    • System.out
    • From a File java.io.File (by constructing a FileOutputStream java.io.FileOutputStream )
    • From a Socket java.net.Socket (using the getOutputStream method)
  2. Create an OutputStreamWriter java.io.OutputStreamWriter (from the OutputStream java.io.OutputStream )
  3. Create a PrintWriter java.io.PrintWriter (from the OutputStreamWriter java.io.OutputStreamWriter )
A Simple Example
javaexamples/iobasics/WriterReaderExample.java
        import java.io.*;

/**
 * A simple exho application that demonstrates character-based I/O in Java.
 *
 * @author  Prof. David Bernstein, James Madison University
 * @version 1.0
 */
public class WriterReaderExample
{
    /**
     * The entry point of the application
     *
     * @param args   The command-line arguments
     */
    public static void main(String[] args) throws IOException
    {
        BufferedReader  in;
        PrintWriter     out;
        String          s;


        in = new BufferedReader(new InputStreamReader(System.in));
        out = new PrintWriter(System.out);

        out.print("Enter a word: ");
        out.flush();

        s = in.readLine();

        out.print("\nYou typed: " + s + "\n");
        out.flush();
    }
}
        
The Benefits of Decorating Streams

An Example

javaexamples/iobasics/ReaderExample.java
        import java.io.*;
import java.net.*;

/**
 * An example that illustrates the flexibility of I/O streams
 * in Java
 *
 * -k              To use the keyboard
 * -f filename     To use a file (e.g., cs.txt)
 * -u url          To use a URL  (e.g., http://www.cs.jmu.edu/common/coursedocs/BernsteinMaterials/javaexamples/iobasics/cs.txt)
 */
public class ReaderExample
{
    /**
     * The entry point of the application
     *
     * @param args   The command-line arguments
     */
    public static void main(String[] args) throws IOException
    {
        BufferedReader       in;
        FileReader           fileReader;
        InputStreamReader    isReader;
        PrintWriter          out;
        String               line;
        URL                  url;


        in = null;

        // Construct the appropriate kind of BufferedReader based
        // on the command-line options
        if (args[0].equals("-f")) {         // Read from a file

            fileReader = new FileReader(args[1]);
            in = new BufferedReader(fileReader);

        } else if (args[0].equals("-u")) { // Read from a URL

            url = new URL(args[1]);
            isReader = new InputStreamReader(url.openStream());
            in = new BufferedReader(isReader);

        } else {                         // Read from the keyboard

            isReader = new InputStreamReader(System.in);
            in = new BufferedReader(isReader);
        }


        out = new PrintWriter(System.out);

        // Keep reading and printing until EOF
        do {

            line = in.readLine();
            if (line != null) {
                out.println(line);
                out.flush();
            }

        } while (line != null);
    }




}
        
Processing Text Output
Processing Text Output (cont.)

An Example that Formats "Choices"

javaexamples/iobasics/ChoiceFormatExample.java
        import java.io.*;
import java.text.*;

/**
 * An example that illustrates the use of the NumberFormat
 * class
 */
public class ChoiceFormatExample
{
    /**
     * The entry point of the application
     *
     * @param args   The command-line arguments
     */
    public static void main(String[] args) throws IOException
    {
        ChoiceFormat          formatter;
        double                grade;
                              // The intervals are half-open [low, high)
        double[]              limits =       { 0, 60, 70, 80, 90};
        String[]              letterGrades = {"F","D","C","B","A"};
        String                outputString;


        // Note that the constuctor is used (unlike NumberFormat)
        formatter = new ChoiceFormat(limits, letterGrades);

        grade = 82.5;
        outputString = formatter.format(grade);

        System.out.println("Numeric Grade: "+grade);
        System.out.println("Letter  Grade: "+outputString);
    }
}
        
Processing Text Output (cont.)
Processing Text Output (cont.)

An Example that Formats Numbers

javaexamples/iobasics/NumberFormatExample.java
        import java.io.*;
import java.text.*;
import java.util.Locale;

/**
 * An example that illustrates the use of the NumberFormat
 * class
 */
public class NumberFormatExample
{
    /**
     * The entry point of the application
     *
     * @param args   The command-line arguments
     */
    public static void main(String[] args) throws IOException
    {
        NumberFormat          formatter;
        String                outputString;


        // Note that the constuctor is often not used directly
        formatter = NumberFormat.getInstance();

        // An example similar to %d in printf
        formatter.setMinimumIntegerDigits(5);
        formatter.setGroupingUsed(false);
        outputString = formatter.format(20);
        System.out.println(outputString);

        // An example similar to %f in printf
        formatter.setMinimumIntegerDigits(0);
        formatter.setMaximumFractionDigits(2);
        formatter.setGroupingUsed(false);
        outputString = formatter.format(1052.2891554);
        System.out.println(outputString);

        // An example that prints currency values
        formatter = NumberFormat.getCurrencyInstance();
        outputString = formatter.format(1953249.25);
        System.out.println(outputString);


        // An example that prints currency values in a different locale
        formatter = NumberFormat.getCurrencyInstance(Locale.GERMANY);
        outputString = formatter.format(1953249.25);
        System.out.println(outputString);


        
    }
}
        
Processing Text Input
Processing Text Input (cont.)
Processing Input (cont.)

Using the StringTokenizer

javaexamples/iobasics/FacultyRecordTokenizer.java
        import java.io.*;
import java.util.*;

/**
 * An example that illustrates the use of reading from a file
 * and using the StringTokenizer class.
 *
 * @author  Prof. David Bernstein, James Madison University
 * @version 1.0
 */
public class FacultyRecordTokenizer
{
    /**
     * The entry point of the application
     *
     * @param args   The command-line arguments
     */
    public static void main(String[] args)
    {
        BufferedReader       in;
        FileReader           fileReader;
        InputStreamReader    isReader;
        String               delimiters, email, line, name, phone;
        StringTokenizer      tokenizer;


        try
        {
            // Setup the reader and writer
            fileReader = new FileReader("cs.txt");
            in = new BufferedReader(fileReader);
            
            // Keep reading, tokenizing and processing
            while ((line = in.readLine()) != null)
            {
                tokenizer = new StringTokenizer(line, "\t", false);
                while (tokenizer.hasMoreTokens()) 
                {
                    try
                    {
                        name = tokenizer.nextToken();
                        phone = tokenizer.nextToken();
                        email = tokenizer.nextToken();
                        
                        // Do something with the information

                    }
                    catch (NoSuchElementException nsee)
                    {
                        // Do something when there is a problem
                    }
                }
            }
            in.close();
        }
        catch (IOException ioe)
        {
            System.err.println("IO Problem");
        }
    }
}
        
Processing Input (cont.)

Using the parse___() Methods

javaexamples/iobasics/ExpressionTokenizer.java
        import java.io.*;
import java.util.*;

/**
 * An example that illustrates the use of the
 * StringTokenizer class
 *
 * @author  Prof. David Bernstein, James Madison University
 * @version 1.0
 */
public class ExpressionTokenizer
{
    /**
     * The entry point of the application
     *
     * @param args   The command-line arguments
     */
    public static void main(String[] args) throws IOException
    {
        double                 value;
        String                 token;
        StringTokenizer        tokenizer;


        // Setup the delimiters
        if (args.length == 0) {

            System.out.println("You didn't enter an expression!");

        } else {

            tokenizer = new StringTokenizer(args[0], 
                                            "+-x/%() \t\n",
                                            true);   // Return delimiters

            // Tokenize the argument
            while (tokenizer.hasMoreTokens()) {

                token = tokenizer.nextToken();
                System.out.print(token);
                System.out.flush();

                // Try to convert the token into a double
                try {

                    value = Double.parseDouble(token);
                    System.out.print(" is a number");
                    System.out.flush();

                } catch (NumberFormatException nfe) {
                    
                    System.out.print(" is not a number");
                    System.out.flush();
                }

                System.out.println();
            }
        }
    }




}
        
Processing Input (cont.)
Processing Input (cont.)

A Comparison of StringTokenizer and String.split()

javaexamples/iobasics/BufferedReaderExample.java
        import java.io.*;
import java.util.*;



/**
 * An example that illustrates the use of the Scanner class
 *
 * @author  Prof. David Bernstein, James Madison University
 * @version 1.0
 */
public class BufferedReaderExample
{
    /**
     * The entry point of the application
     *
     * @param args   The command-line arguments
     * @throws IOException if any line can't be read
     */
    public static void main(String[] args) throws IOException
    {
        BufferedReader      in;
        double              salary;        
        InputStreamReader   isr;
        int                 age, weight;        
        String              line, name, phone;
        String[]            tokens;
        StringTokenizer     st;        

        isr = new InputStreamReader(System.in);
        in  = new BufferedReader(isr);

        System.out.print("Name: ");
        name = in.readLine();

        System.out.print("Salary: ");
        line   = in.readLine();
        salary = Double.parseDouble(line);

        System.out.print("Phone number (###-###-####): ");
        phone = in.readLine();

        System.out.print("Age Weight (# #): ");
        line   = in.readLine();
        // One way to tokenize: Using the split() method
        tokens = line.split(" ");
        age    = Integer.parseInt(tokens[0]);
        weight = Integer.parseInt(tokens[1]);
        // Another way to tokenize: Using a StringTokenizer
        st     = new StringTokenizer(line, " ");
        age    = Integer.parseInt(st.nextToken());
        weight = Integer.parseInt(st.nextToken());
        

        in.close();
    }
    
    
}