1 18 package org.apache.tools.ant.util; 19 20 import java.io.IOException ; 21 import java.io.InputStream ; 22 import java.io.Reader ; 23 24 29 public class ReaderInputStream extends InputStream { 30 31 32 private Reader in; 33 34 private String encoding = System.getProperty("file.encoding"); 35 36 private byte[] slack; 37 38 private int begin; 39 40 46 public ReaderInputStream(Reader reader) { 47 in = reader; 48 } 49 50 58 public ReaderInputStream(Reader reader, String encoding) { 59 this(reader); 60 if (encoding == null) { 61 throw new IllegalArgumentException ("encoding must not be null"); 62 } else { 63 this.encoding = encoding; 64 } 65 } 66 67 74 public synchronized int read() throws IOException { 75 if (in == null) { 76 throw new IOException ("Stream Closed"); 77 } 78 79 byte result; 80 if (slack != null && begin < slack.length) { 81 result = slack[begin]; 82 if (++begin == slack.length) { 83 slack = null; 84 } 85 } else { 86 byte[] buf = new byte[1]; 87 if (read(buf, 0, 1) <= 0) { 88 return -1; 89 } else { 90 result = buf[0]; 91 } 92 } 93 94 return result & 0xFF; 95 } 96 97 107 public synchronized int read(byte[] b, int off, int len) 108 throws IOException { 109 if (in == null) { 110 throw new IOException ("Stream Closed"); 111 } 112 if (len == 0) { 113 return 0; 114 } 115 while (slack == null) { 116 char[] buf = new char[len]; int n = in.read(buf); 118 if (n == -1) { 119 return -1; 120 } 121 if (n > 0) { 122 slack = new String (buf, 0, n).getBytes(encoding); 123 begin = 0; 124 } 125 } 126 127 if (len > slack.length - begin) { 128 len = slack.length - begin; 129 } 130 131 System.arraycopy(slack, begin, b, off, len); 132 133 if ((begin += len) >= slack.length) { 134 slack = null; 135 } 136 137 return len; 138 } 139 140 146 public synchronized void mark(final int limit) { 147 try { 148 in.mark(limit); 149 } catch (IOException ioe) { 150 throw new RuntimeException (ioe.getMessage()); 151 } 152 } 153 154 155 159 public synchronized int available() throws IOException { 160 if (in == null) { 161 throw new IOException ("Stream Closed"); 162 } 163 if (slack != null) { 164 return slack.length - begin; 165 } 166 if (in.ready()) { 167 return 1; 168 } else { 169 return 0; 170 } 171 } 172 173 176 public boolean markSupported () { 177 return false; } 179 180 185 public synchronized void reset() throws IOException { 186 if (in == null) { 187 throw new IOException ("Stream Closed"); 188 } 189 slack = null; 190 in.reset(); 191 } 192 193 198 public synchronized void close() throws IOException { 199 if (in != null) { 200 in.close(); 201 slack = null; 202 in = null; 203 } 204 } 205 } 206 | Popular Tags |