JMU
Character Input and Output in Java
An Introduction


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu


Review of Console I/O
General Character-Based I/O
Obtaining Other Input/Output Streams
Input with a Scanner
Input with a Scanner (cont.)
Input with a BufferedReader
Tokenizing Input
An Example that Uses a Scanner (cont.)
javaexamples/iobasics/ScannerExample.java
import java.util.Scanner;

/**
 * An example that illustrates the use of the Scanner class
 *
 * @author  Prof. David Bernstein, James Madison University
 * @version 1.0
 */
public class ScannerExample
{
    /**
     * The entry point of the application
     *
     * @param args   The command-line arguments
     */
    public static void main(String[] args)
    {
       int        age, weight;
       double     salary;
       Scanner    keyboard;
       String     line, name;
       String[]   parts;       
       
       keyboard = new Scanner(System.in);
       
       System.out.print("Name: ");
       name = keyboard.nextLine();

       System.out.print("Salary: ");
       salary = keyboard.nextDouble();
       keyboard.nextLine(); // Consume the end-of-line character

       System.out.print("Phone number (###-###-####): ");
       line   = keyboard.nextLine();

       System.out.print("Age Weight (# #): ");
       age    = keyboard.nextInt();
       weight = keyboard.nextInt();

       keyboard.close();       
    }
}
        
An Example that Uses a BufferedReader (cont.)
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();
    }
    
    
}
        
Reading Until End-of-Stream

Using a while Loop

javaexamples/iobasics/EndOfStreamExample.java (Fragment: while)
        // Read the first line
        try
        {
            line = in.readLine();
            while (line != null)
            {
                // Process the input
                
                // Read subsequent lines
                line = in.readLine();
            }
        }
        catch (IOException ioe)
        {
            // Handle the exception
        }
    
        
Reading Until End-of-Stream (cont.)

Using a do-while Loop

javaexamples/iobasics/EndOfStreamExample.java (Fragment: do)
        try
        {
            do
            {
                // Read a line
                line = in.readLine();
                
                if (line != null)
                {
                    // Process the input
                }
            } while (line != null);
        }
        catch (IOException ioe)
        {
            // Handle the exception
        }
        
Reading Until End-of-Stream (cont.)

Using an Elegant Idiom

javaexamples/iobasics/EndOfStreamExample.java (Fragment: elegant)
        try
        {
            while ((line = in.readLine()) != null)
            {
                // Process the line
            }
        }
        catch (IOException ioe)
        {
            // Handle the exception
        }
        
Output with a PrintWriter
Output with a PrintWriter (cont.)
Formatting Output (cont.)
Going Further: Other Ways to Format Output
Going Further: Internationalizing/Localizing Output
Going Further: Internationalizing/Localizing 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);


        
    }
}
        
Streams from Files
Streams from Files (cont.)

An Example of File Input Using a BufferedReader

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");
        }
    }
}
        
Streams from Files (cont.)

An Example of File Input Using a Scanner

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

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


        try
        {
            // Setup the reader and writer
            in = new Scanner(new File("cs.txt"));
            in.useDelimiter("\t");
            
            // Keep reading and processing until EOF
            while (in.hasNext())
            {
                name = in.next();
                phone = in.next();
                email = in.nextLine(); // Also consume the end-of-line character
                email = email.substring(1); // Strip-off the leading delimiter
                            
                // Do something with the information

            }
            in.close();
        }
        catch (IOException ioeFile)
        {
            System.err.println("Unable to open the file.");
        }
    }
}
        
Streams from Files (cont.)

An Example of File Output

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

/**
 * An application that asks the user simple addition questions.
 *
 * This application demonstrates the use of console I/O and file
 * output.
 *
 * @author  Prof. David Bernstein, James Madison University
 * @version 1.0
 */
public class Quizzer
{
    private static final int NUMBER_OF_QUESTIONS = 10;    

    /**
     * The entry point of the application.
     *
     * @param args  The command-line arguments (which are ignored)
     */
    public static void main(String[] args)
    {
        boolean        status;        
        BufferedReader keyboard;
        int            actual, correct, expected, left, right;
        PrintWriter    log;        
        Random         rng;
        String         line;
        
        correct  = 0;        
        rng      = new Random();
        keyboard = new BufferedReader(new InputStreamReader(System.in));

        // Ask the questions and check the answers
        for (int i=0; i<NUMBER_OF_QUESTIONS; i++)
        {
            left  = rng.nextInt(10);
            right = rng.nextInt(10);
            expected = left + right;

            System.out.printf("%d. What is %d + %d? ", i+1, left, right);
            try
            {
                line = keyboard.readLine();
                try
                {
                    actual  = Integer.parseInt(line);
                    status = (actual == expected);                
                }
                catch (NumberFormatException nfe)
                {
                    status = false;
                }
            }
            catch (IOException ioe)
            {
                status = false;
            }
            
            if (status)
            {
                ++correct;
                System.out.printf("Correct!\n");
            }
            else
            {
                System.out.printf("Sorry, that's not correct.\n");
            }
        }

        // Create a log file that contains a summary of the results
        try
        {
            log = new PrintWriter(new File("results.txt"));
            log.printf("Correct:   %2d\n", correct);
            log.printf("Incorrect: %2d\n", NUMBER_OF_QUESTIONS - correct);
            log.close();
        }
        catch (FileNotFoundException fnfe)
        {
            System.out.printf("Unable to create the log file.");
        }
    }
    

}