1 15 package org.apache.tapestry.util.text; 16 17 import java.io.IOException ; 18 import java.io.Reader ; 19 20 26 public class ExtendedReader extends Reader 27 { 28 private Reader _reader; 29 private boolean _hasBufferedChar = false; 30 private char _bufferedChar; 31 32 37 public ExtendedReader(Reader in) 38 { 39 _reader = in; 40 } 41 42 49 public synchronized int peek() throws IOException 50 { 51 if (!_hasBufferedChar) { 52 int bufferedChar = read(); 53 if (bufferedChar < 0) 54 return bufferedChar; 55 _bufferedChar = (char) bufferedChar; 56 _hasBufferedChar = true; 57 } 58 return _bufferedChar; 59 } 60 61 67 public synchronized boolean isEndOfStream() throws IOException 68 { 69 return peek() < 0; 70 } 71 72 78 public synchronized void skipCharacters(ICharacterMatcher matcher) throws IOException 79 { 80 while (true) { 81 if (isEndOfStream()) 82 break; 83 char ch = (char) peek(); 84 if (!matcher.matches(ch)) 85 break; 86 read(); 87 } 88 } 89 90 97 public synchronized String readCharacters(ICharacterMatcher matcher) throws IOException 98 { 99 StringBuffer buf = new StringBuffer (); 100 while (true) { 101 if (isEndOfStream()) 102 break; 103 char ch = (char) peek(); 104 if (!matcher.matches(ch)) 105 break; 106 buf.append(read()); 107 } 108 return buf.toString(); 109 } 110 111 114 public synchronized int read(char[] cbuf, int off, int len) throws IOException 115 { 116 if (len <= 0) 117 return 0; 118 119 boolean extraChar = _hasBufferedChar; 120 if (_hasBufferedChar) { 121 _hasBufferedChar = false; 122 cbuf[off++] = _bufferedChar; 123 len--; 124 } 125 126 int read = _reader.read(cbuf, off, len); 127 if (extraChar) 128 read++; 129 return read; 130 } 131 132 135 public synchronized boolean ready() throws IOException 136 { 137 if (_hasBufferedChar) 138 return true; 139 return _reader.ready(); 140 } 141 142 145 public synchronized boolean markSupported() 146 { 147 return false; 148 } 149 150 153 public synchronized void reset() throws IOException 154 { 155 _hasBufferedChar = false; 156 _reader.reset(); 157 } 158 159 162 public synchronized long skip(long n) throws IOException 163 { 164 if (_hasBufferedChar && n > 0) { 165 _hasBufferedChar = false; 166 n--; 167 } 168 return _reader.skip(n); 169 } 170 171 174 public synchronized void close() throws IOException 175 { 176 _hasBufferedChar = false; 177 _reader.close(); 178 } 179 180 } 181 | Popular Tags |