import java.io.*; import java.util.Random; // invoke 4 different ways: // 1. java TestPart1 10 10 30 < p5.html > testPart1.out1 // 2. java TestPart1 10 30 10 < p5.html > testPart1.out2 // 3. java TestPart1 100 10 30 < TestPart1.java > testPart1.out3 // 4. java TestPart1 100 30 10 < TestPart1.java > testPart1.out4 // for all cases, the output file should be identical to the input file - // check with diff or cmp public class TestPart1 { static Random RNG = new Random(); static int BufSize = 10; // default buffer size static int readerSleep = 100; // default reader sleep value static int writerSleep = 300; // default writer sleep value static public void sleepRandomly( int max ) { try { Thread.sleep( RNG.nextInt( max ) ); } catch ( InterruptedException e ) { } } static public void main(String args[]) { if( args.length == 3 ) { try { BufSize = Integer.parseInt( args[0] ); readerSleep = Integer.parseInt( args[1] ); writerSleep = Integer.parseInt( args[2] ); } catch( NumberFormatException e ) { System.err.println( "[USAGE] java TestBuf " ); return; } } else if( args.length != 0 ) { System.err.println( "[USAGE] java TestBuf " ); return; } final InputStreamReader in = new InputStreamReader(System.in); final PrintWriter out = new PrintWriter(System.out, true ); // This is the class being tested final FilterBuffer buf = new FilterBufferImpl(BufSize); // Read Thread: reads data from buffer and put to "out" Thread reader = new Thread() { public void run() { while( true ) { // blocks if it's empty and still open char[] data = buf.read(); // no more data and closed if( data.length == 0 ) { out.flush(); break; } out.print( data ); out.flush(); sleepRandomly( readerSleep ); } } }; reader.start(); // Write Thread: reads data from "in" and put to Buffer // writer writes character by character Thread writer = new Thread() { public void run() { while( true ) { char[] c = new char[1]; try { // read one character from "in" if( in.read( c, 0, 1) == -1 ) { //reached end of stream buf.flush(); buf.close(); break; } buf.write( c ); }catch( bufTooSmallException e ) { sleepRandomly( writerSleep ); continue; }catch( IOException e ) { e.printStackTrace(); return; } } } }; writer.start(); try { reader.join(); writer.join(); } catch ( InterruptedException e ) { } return; } }