package duckMachine.architecture; import java.io.*; /** * The input output unit of the machine. This will not work with jdk-1.0! * @author Amr Sabry * @version jdk-1.1 */ public class ioUnit implements ioUnitI { /** * The dataReader converts bytes to chars using an InputStreamReader * (buffered for efficiency) and then collects the chars and parses * them as ints using a StreamTokenizer. */ private StreamTokenizer dataReader; /** * The dataWriter stream is built on top of the byte-oriented stream * by wrapping an OutputStreamWriter that can handle chars, and then * a PrintWriter than can handle strings. The output is buffered * for efficiency and is automatically flushed when a newline is printed. */ private PrintWriter dataWriter; public ioUnit () { this(DEFAULT_ISTREAM, DEFAULT_OSTREAM); } public ioUnit (InputStream i, OutputStream o) { Reader charReader = new BufferedReader (new InputStreamReader (i)); dataReader = new StreamTokenizer (charReader); Writer charWriter = new BufferedWriter (new OutputStreamWriter (o)); boolean automaticFlushAtNewline = true; dataWriter = new PrintWriter (charWriter, automaticFlushAtNewline); } public StreamTokenizer getReader () { return dataReader; } public PrintWriter getWriter () { return dataWriter; } /** * Reads an integer from the input stream. If the next * token is a number but not an integer, it is coerced to an int. * @exception ioE If the input cannot be parsed as a number or * some kind of IO exception occurs. */ public Word readData () throws ioE { try { dataReader.nextToken(); if (dataReader.ttype == dataReader.TT_NUMBER) { double d = dataReader.nval; int i = (int)d; return new Data(i); } else throw new ioE("Illegal input"); } catch (java.io.IOException e) { throw new ioE("IO exception occured while reading data\n" + e.toString()); } } /** * Writes an int and flushes the output stream. */ public void writeData (Word w) { dataWriter.println(w); } }