1 /* 2 * Copyright (c) 1996, 2012, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 package java.io; 27 28 29 import java.nio.CharBuffer; 30 import java.util.Objects; 31 32 /** 33 * Abstract class for reading character streams. The only methods that a 34 * subclass must implement are read(char[], int, int) and close(). Most 35 * subclasses, however, will override some of the methods defined here in order 36 * to provide higher efficiency, additional functionality, or both. 37 * 38 * 39 * @see BufferedReader 40 * @see LineNumberReader 41 * @see CharArrayReader 42 * @see InputStreamReader 43 * @see FileReader 44 * @see FilterReader 45 * @see PushbackReader 46 * @see PipedReader 47 * @see StringReader 48 * @see Writer 49 * 50 * @author Mark Reinhold 51 * @since 1.1 52 */ 53 54 public abstract class Reader implements Readable, Closeable { 55 56 private static final int TRANSFER_BUFFER_SIZE = 8192; 57 58 /** 59 * Returns a new {@code Reader} that reads no characters. The returned 60 * stream is initially open. The stream is closed by calling the 61 * {@code close()} method. Subsequent calls to {@code close()} have no 62 * effect. 63 * 64 * <p> While the stream is open, the {@code read()}, {@code read(char[])}, 65 * {@code read(char[], int, int)}, {@code read(Charbuffer)}, {@code 66 * ready()}, {@code skip(long)}, and {@code transferTo()} methods all 67 * behave as if end of stream has been reached. After the stream has been 68 * closed, these methods all throw {@code IOException}. 69 * 70 * <p> The {@code markSupported()} method returns {@code false}. The 71 * {@code mark()} and {@code reset()} methods throw an {@code IOException}. 72 * 73 * <p> The {@link #lock object} used to synchronize operations on the 74 * returned {@code Reader} is not specified. 75 * 76 * @return a {@code Reader} which reads no characters 77 * 78 * @since 11 79 */ nullReader()80 public static Reader nullReader() { 81 return new Reader() { 82 private volatile boolean closed; 83 84 private void ensureOpen() throws IOException { 85 if (closed) { 86 throw new IOException("Stream closed"); 87 } 88 } 89 90 @Override 91 public int read() throws IOException { 92 ensureOpen(); 93 return -1; 94 } 95 96 @Override 97 public int read(char[] cbuf, int off, int len) throws IOException { 98 Objects.checkFromIndexSize(off, len, cbuf.length); 99 ensureOpen(); 100 if (len == 0) { 101 return 0; 102 } 103 return -1; 104 } 105 106 @Override 107 public int read(CharBuffer target) throws IOException { 108 Objects.requireNonNull(target); 109 ensureOpen(); 110 if (target.hasRemaining()) { 111 return -1; 112 } 113 return 0; 114 } 115 116 @Override 117 public boolean ready() throws IOException { 118 ensureOpen(); 119 return false; 120 } 121 122 @Override 123 public long skip(long n) throws IOException { 124 ensureOpen(); 125 return 0L; 126 } 127 128 @Override 129 public long transferTo(Writer out) throws IOException { 130 Objects.requireNonNull(out); 131 ensureOpen(); 132 return 0L; 133 } 134 135 @Override 136 public void close() { 137 closed = true; 138 } 139 }; 140 } 141 142 /** 143 * The object used to synchronize operations on this stream. For 144 * efficiency, a character-stream object may use an object other than 145 * itself to protect critical sections. A subclass should therefore use 146 * the object in this field rather than {@code this} or a synchronized 147 * method. 148 */ 149 protected Object lock; 150 151 /** 152 * Creates a new character-stream reader whose critical sections will 153 * synchronize on the reader itself. 154 */ Reader()155 protected Reader() { 156 this.lock = this; 157 } 158 159 /** 160 * Creates a new character-stream reader whose critical sections will 161 * synchronize on the given object. 162 * 163 * @param lock The Object to synchronize on. 164 */ Reader(Object lock)165 protected Reader(Object lock) { 166 if (lock == null) { 167 throw new NullPointerException(); 168 } 169 this.lock = lock; 170 } 171 172 /** 173 * Attempts to read characters into the specified character buffer. 174 * The buffer is used as a repository of characters as-is: the only 175 * changes made are the results of a put operation. No flipping or 176 * rewinding of the buffer is performed. 177 * 178 * @param target the buffer to read characters into 179 * @return The number of characters added to the buffer, or 180 * -1 if this source of characters is at its end 181 * @throws IOException if an I/O error occurs 182 * @throws NullPointerException if target is null 183 * @throws java.nio.ReadOnlyBufferException if target is a read only buffer 184 * @since 1.5 185 */ read(java.nio.CharBuffer target)186 public int read(java.nio.CharBuffer target) throws IOException { 187 int len = target.remaining(); 188 char[] cbuf = new char[len]; 189 int n = read(cbuf, 0, len); 190 if (n > 0) 191 target.put(cbuf, 0, n); 192 return n; 193 } 194 195 /** 196 * Reads a single character. This method will block until a character is 197 * available, an I/O error occurs, or the end of the stream is reached. 198 * 199 * <p> Subclasses that intend to support efficient single-character input 200 * should override this method. 201 * 202 * @return The character read, as an integer in the range 0 to 65535 203 * ({@code 0x00-0xffff}), or -1 if the end of the stream has 204 * been reached 205 * 206 * @exception IOException If an I/O error occurs 207 */ read()208 public int read() throws IOException { 209 char cb[] = new char[1]; 210 if (read(cb, 0, 1) == -1) 211 return -1; 212 else 213 return cb[0]; 214 } 215 216 /** 217 * Reads characters into an array. This method will block until some input 218 * is available, an I/O error occurs, or the end of the stream is reached. 219 * 220 * @param cbuf Destination buffer 221 * 222 * @return The number of characters read, or -1 223 * if the end of the stream 224 * has been reached 225 * 226 * @exception IOException If an I/O error occurs 227 */ read(char cbuf[])228 public int read(char cbuf[]) throws IOException { 229 return read(cbuf, 0, cbuf.length); 230 } 231 232 /** 233 * Reads characters into a portion of an array. This method will block 234 * until some input is available, an I/O error occurs, or the end of the 235 * stream is reached. 236 * 237 * @param cbuf Destination buffer 238 * @param off Offset at which to start storing characters 239 * @param len Maximum number of characters to read 240 * 241 * @return The number of characters read, or -1 if the end of the 242 * stream has been reached 243 * 244 * @exception IOException If an I/O error occurs 245 * @exception IndexOutOfBoundsException 246 * If {@code off} is negative, or {@code len} is negative, 247 * or {@code len} is greater than {@code cbuf.length - off} 248 */ read(char cbuf[], int off, int len)249 public abstract int read(char cbuf[], int off, int len) throws IOException; 250 251 /** Maximum skip-buffer size */ 252 private static final int maxSkipBufferSize = 8192; 253 254 /** Skip buffer, null until allocated */ 255 private char skipBuffer[] = null; 256 257 /** 258 * Skips characters. This method will block until some characters are 259 * available, an I/O error occurs, or the end of the stream is reached. 260 * 261 * @param n The number of characters to skip 262 * 263 * @return The number of characters actually skipped 264 * 265 * @exception IllegalArgumentException If <code>n</code> is negative. 266 * @exception IOException If an I/O error occurs 267 */ skip(long n)268 public long skip(long n) throws IOException { 269 if (n < 0L) 270 throw new IllegalArgumentException("skip value is negative"); 271 int nn = (int) Math.min(n, maxSkipBufferSize); 272 synchronized (lock) { 273 if ((skipBuffer == null) || (skipBuffer.length < nn)) 274 skipBuffer = new char[nn]; 275 long r = n; 276 while (r > 0) { 277 int nc = read(skipBuffer, 0, (int)Math.min(r, nn)); 278 if (nc == -1) 279 break; 280 r -= nc; 281 } 282 return n - r; 283 } 284 } 285 286 /** 287 * Tells whether this stream is ready to be read. 288 * 289 * @return True if the next read() is guaranteed not to block for input, 290 * false otherwise. Note that returning false does not guarantee that the 291 * next read will block. 292 * 293 * @exception IOException If an I/O error occurs 294 */ ready()295 public boolean ready() throws IOException { 296 return false; 297 } 298 299 /** 300 * Tells whether this stream supports the mark() operation. The default 301 * implementation always returns false. Subclasses should override this 302 * method. 303 * 304 * @return true if and only if this stream supports the mark operation. 305 */ markSupported()306 public boolean markSupported() { 307 return false; 308 } 309 310 /** 311 * Marks the present position in the stream. Subsequent calls to reset() 312 * will attempt to reposition the stream to this point. Not all 313 * character-input streams support the mark() operation. 314 * 315 * @param readAheadLimit Limit on the number of characters that may be 316 * read while still preserving the mark. After 317 * reading this many characters, attempting to 318 * reset the stream may fail. 319 * 320 * @exception IOException If the stream does not support mark(), 321 * or if some other I/O error occurs 322 */ mark(int readAheadLimit)323 public void mark(int readAheadLimit) throws IOException { 324 throw new IOException("mark() not supported"); 325 } 326 327 /** 328 * Resets the stream. If the stream has been marked, then attempt to 329 * reposition it at the mark. If the stream has not been marked, then 330 * attempt to reset it in some way appropriate to the particular stream, 331 * for example by repositioning it to its starting point. Not all 332 * character-input streams support the reset() operation, and some support 333 * reset() without supporting mark(). 334 * 335 * @exception IOException If the stream has not been marked, 336 * or if the mark has been invalidated, 337 * or if the stream does not support reset(), 338 * or if some other I/O error occurs 339 */ reset()340 public void reset() throws IOException { 341 throw new IOException("reset() not supported"); 342 } 343 344 /** 345 * Closes the stream and releases any system resources associated with 346 * it. Once the stream has been closed, further read(), ready(), 347 * mark(), reset(), or skip() invocations will throw an IOException. 348 * Closing a previously closed stream has no effect. 349 * 350 * @exception IOException If an I/O error occurs 351 */ close()352 public abstract void close() throws IOException; 353 354 /** 355 * Reads all characters from this reader and writes the characters to the 356 * given writer in the order that they are read. On return, this reader 357 * will be at end of the stream. This method does not close either reader 358 * or writer. 359 * <p> 360 * This method may block indefinitely reading from the reader, or 361 * writing to the writer. The behavior for the case where the reader 362 * and/or writer is <i>asynchronously closed</i>, or the thread 363 * interrupted during the transfer, is highly reader and writer 364 * specific, and therefore not specified. 365 * <p> 366 * If an I/O error occurs reading from the reader or writing to the 367 * writer, then it may do so after some characters have been read or 368 * written. Consequently the reader may not be at end of the stream and 369 * one, or both, streams may be in an inconsistent state. It is strongly 370 * recommended that both streams be promptly closed if an I/O error occurs. 371 * 372 * @param out the writer, non-null 373 * @return the number of characters transferred 374 * @throws IOException if an I/O error occurs when reading or writing 375 * @throws NullPointerException if {@code out} is {@code null} 376 * 377 * @since 10 378 */ transferTo(Writer out)379 public long transferTo(Writer out) throws IOException { 380 Objects.requireNonNull(out, "out"); 381 long transferred = 0; 382 char[] buffer = new char[TRANSFER_BUFFER_SIZE]; 383 int nRead; 384 while ((nRead = read(buffer, 0, TRANSFER_BUFFER_SIZE)) >= 0) { 385 out.write(buffer, 0, nRead); 386 transferred += nRead; 387 } 388 return transferred; 389 } 390 391 } 392