INTRODUCTION TO COMPUTER SCIENCE
Robert Sedgewick and Kevin Wayne


This is the syntax highlighted version of CharStdIn.java.

/*************************************************************************
 *  Compilation:  javac CharStdIn.java
 *  Execution:    java CharStdIn
 *  
 *  Supports reading variables of type char from stdin.
 *  For use with ASCII and not UNICODE since we read a byte at a time.
 *
 *  Not buffered -> not very efficient.
 * 
 *************************************************************************/

 import java.io.IOException;

 public class CharStdIn {
    private static final int EOF = -1;     // end of file
    private static int c = EOF;            // one character buffer

    // return EOF if end of file or IO error
    public static boolean isEmpty() {
        if (c == EOF) {
            try { c = System.in.read(); }
            catch(IOException e) { c = EOF; }
        }
        return (c == EOF);
    }


    // return EOF if end of file or IO error
    public static char readChar() {
        if (isEmpty()) throw new RuntimeException("Reading from empty input stream");
        char ch = (char) c;
        c = EOF;
        return ch;
    }
    

    // return rest of line as string
    public static String readLine() {
        StringBuffer sb = new StringBuffer();
        while(!isEmpty()) {
            char c = readChar();
            sb.append(c);
            if (c == '\n') break;
        }
        String s = sb.toString();
        if (s.endsWith("\r\n")) return s.substring(0, s.length() - 2);     // DOS
        if (s.endsWith("\n"))   return s.substring(0, s.length() - 1);     // Unix
        return s;
    }

    // return rest of input as string, use StringBuffer to avoid quadratic run time
    public static String readAll() {
        StringBuffer sb = new StringBuffer();
        while(!isEmpty())
            sb.append(readChar());
        String s = sb.toString();
        return s;
    }



   // echo test client
   public static void main(String[] args) {
       while (!CharStdIn.isEmpty()) {
           System.out.print(CharStdIn.readChar());
       }

   }

}


Last updated: Sat Mar 20 07:27:51 EST 2004 .
Copyright © 2004, Robert Sedgewick and Kevin Wayne.