1 17 18 package org.mmbase.util; 20 21 import java.io.*; 22 23 import org.mmbase.util.logging.*; 24 25 26 35 36 37 public class ReaderInputStream extends InputStream { 38 private static Logger log = Logging.getLoggerInstance(ReaderInputStream.class); 39 40 private Reader in; 41 42 private String encoding = System.getProperty("file.encoding"); 43 44 private byte[] slack; 45 46 private int begin; 47 48 54 public ReaderInputStream(Reader reader) { 55 in = reader; 56 } 57 58 66 public ReaderInputStream(Reader reader, String encoding) { 67 this(reader); 68 if (encoding == null) { 69 throw new IllegalArgumentException ("encoding must not be null"); 70 } else { 71 this.encoding = encoding; 72 } 73 } 74 75 82 public synchronized int read() throws IOException { 83 if (in == null) { 84 throw new IOException("Stream Closed"); 85 } 86 87 byte result; 88 if (slack != null && begin < slack.length) { 89 result = slack[begin]; 90 if (++begin == slack.length) { 91 slack = null; 92 } 93 } else { 94 byte[] buf = new byte[1]; 95 if (read(buf, 0, 1) <= 0) { 96 result = -1; 97 } else { 98 result = buf[0]; 99 } 100 } 101 102 if (result < -1) { 103 result += 256; 104 } 105 106 return result; 107 } 108 109 119 public synchronized int read(byte[] b, int off, int len) 120 throws IOException { 121 if (in == null) { 122 throw new IOException("Stream Closed"); 123 } 124 125 while (slack == null) { 126 char[] buf = new char[len]; int n = in.read(buf); 128 if (n == -1) { 129 return -1; 130 } 131 if (n > 0) { 132 slack = new String (buf, 0, n).getBytes(encoding); 133 begin = 0; 134 } 135 } 136 137 if (len > slack.length - begin) { 138 len = slack.length - begin; 139 } 140 141 System.arraycopy(slack, begin, b, off, len); 142 143 if ((begin += len) >= slack.length) { 144 slack = null; 145 } 146 147 return len; 148 } 149 150 156 public synchronized void mark(final int limit) { 157 try { 158 in.mark(limit); 159 } catch (IOException ioe) { 160 throw new RuntimeException (ioe.getMessage()); 161 } 162 } 163 164 165 169 public synchronized int available() throws IOException { 170 if (in == null) { 171 throw new IOException("Stream Closed"); 172 } 173 if (slack != null) { 174 return slack.length - begin; 175 } 176 if (in.ready()) { 177 return 1; 178 } else { 179 return 0; 180 } 181 } 182 183 186 public boolean markSupported () { 187 return false; } 189 190 195 public synchronized void reset() throws IOException { 196 if (in == null) { 197 throw new IOException("Stream Closed"); 198 } 199 slack = null; 200 in.reset(); 201 } 202 203 208 public synchronized void close() throws IOException { 209 in.close(); 210 slack = null; 211 in = null; 212 } 213 214 public static void main(String [] args) throws IOException { 215 ReaderInputStream is = new ReaderInputStream(new StringReader(args[0]), "UTF-8"); 216 while (true) { 217 int b = is.read(); 218 if (b <= 0) break; 219 System.out.println("" + b); 220 } 221 } 222 } 223 | Popular Tags |