1 33 34 package edu.rice.cs.util; 35 36 import java.io.*; 37 import java.util.ArrayList ; 38 39 42 public abstract class InputStreamRedirector extends InputStream { 43 47 protected ArrayList <Character > _buffer; 48 49 50 public InputStreamRedirector() { _buffer = new ArrayList <Character >(60); } 51 52 58 protected abstract String _getInput() throws IOException; 59 60 64 private void _readInputIntoBuffer() throws IOException { 65 String input = _getInput(); 66 if (input.equals("")) throw new IOException("_getInput() must return non-empty input!"); 67 68 for(int i = 0; i < input.length(); i++) { 69 _buffer.add(new Character (input.charAt(i))); 70 } 71 } 72 73 77 public synchronized int read(byte[] b) throws IOException { return read(b, 0, b.length); } 78 79 85 public synchronized int read(byte[] b, int off, int len) throws IOException { 86 int numRead = 0; 87 if (available() == 0) _readInputIntoBuffer(); 88 89 for(int i = off; i < off + len; i++) { 90 if (available() == 0) break; 91 else { 92 b[i] = (byte) _buffer.remove(0).charValue(); 93 numRead++; 94 } 95 } 96 return numRead; 97 } 98 99 103 public synchronized int read() throws IOException { 104 if (available() == 0) _readInputIntoBuffer(); 105 return _buffer.remove(0).charValue(); 106 } 107 108 109 public int available() { return _buffer.size(); } 110 } 111 112 | Popular Tags |