1 /*
   2  * Copyright (c) 1996, 2018, 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()} method does nothing, and the {@code reset()} method
  72      * throws {@code IOException}.
  73      *
  74      * <p> The {@link #lock object} used to synchronize operations on the
  75      * returned {@code Reader} is not specified.
  76      *
  77      * @return a {@code Reader} which reads no characters
  78      *
  79      * @since 11
  80      */
  81     public static Reader nullReader() {
  82         return new Reader() {
  83             private volatile boolean closed;
  84 
  85             private void ensureOpen() throws IOException {
  86                 if (closed) {
  87                     throw new IOException("Stream closed");
  88                 }
  89             }
  90 
  91             @Override
  92             public int read() throws IOException {
  93                 ensureOpen();
  94                 return -1;
  95             }
  96 
  97             @Override
  98             public int read(char[] cbuf, int off, int len) throws IOException {
  99                 Objects.checkFromIndexSize(off, len, cbuf.length);
 100                 ensureOpen();
 101                 if (len == 0) {
 102                     return 0;
 103                 }
 104                 return -1;
 105             }
 106 
 107             @Override
 108             public int read(CharBuffer target) throws IOException {
 109                 Objects.requireNonNull(target);
 110                 ensureOpen();
 111                 if (target.hasRemaining()) {
 112                     return -1;
 113                 }
 114                 return 0;
 115             }
 116 
 117             @Override
 118             public long skip(long n) throws IOException {
 119                 ensureOpen();
 120                 return 0L;
 121             }
 122 
 123             @Override
 124             public long transferTo(Writer out) throws IOException {
 125                 Objects.requireNonNull(out);
 126                 ensureOpen();
 127                 return 0L;
 128             }
 129 
 130             @Override
 131             public void close() {
 132                 closed = true;
 133             }
 134         };
 135     }
 136 
 137     /**
 138      * The object used to synchronize operations on this stream.  For
 139      * efficiency, a character-stream object may use an object other than
 140      * itself to protect critical sections.  A subclass should therefore use
 141      * the object in this field rather than {@code this} or a synchronized
 142      * method.
 143      */
 144     protected Object lock;
 145 
 146     /**
 147      * Creates a new character-stream reader whose critical sections will
 148      * synchronize on the reader itself.
 149      */
 150     protected Reader() {
 151         this.lock = this;
 152     }
 153 
 154     /**
 155      * Creates a new character-stream reader whose critical sections will
 156      * synchronize on the given object.
 157      *
 158      * @param lock  The Object to synchronize on.
 159      */
 160     protected Reader(Object lock) {
 161         if (lock == null) {
 162             throw new NullPointerException();
 163         }
 164         this.lock = lock;
 165     }
 166 
 167     /**
 168      * Attempts to read characters into the specified character buffer.
 169      * The buffer is used as a repository of characters as-is: the only
 170      * changes made are the results of a put operation. No flipping or
 171      * rewinding of the buffer is performed.
 172      *
 173      * @param target the buffer to read characters into
 174      * @return The number of characters added to the buffer, or
 175      *         -1 if this source of characters is at its end
 176      * @throws IOException if an I/O error occurs
 177      * @throws NullPointerException if target is null
 178      * @throws java.nio.ReadOnlyBufferException if target is a read only buffer
 179      * @since 1.5
 180      */
 181     public int read(java.nio.CharBuffer target) throws IOException {
 182         int len = target.remaining();
 183         char[] cbuf = new char[len];
 184         int n = read(cbuf, 0, len);
 185         if (n > 0)
 186             target.put(cbuf, 0, n);
 187         return n;
 188     }
 189 
 190     /**
 191      * Reads a single character.  This method will block until a character is
 192      * available, an I/O error occurs, or the end of the stream is reached.
 193      *
 194      * <p> Subclasses that intend to support efficient single-character input
 195      * should override this method.
 196      *
 197      * @return     The character read, as an integer in the range 0 to 65535
 198      *             ({@code 0x00-0xffff}), or -1 if the end of the stream has
 199      *             been reached
 200      *
 201      * @exception  IOException  If an I/O error occurs
 202      */
 203     public int read() throws IOException {
 204         char cb[] = new char[1];
 205         if (read(cb, 0, 1) == -1)
 206             return -1;
 207         else
 208             return cb[0];
 209     }
 210 
 211     /**
 212      * Reads characters into an array.  This method will block until some input
 213      * is available, an I/O error occurs, or the end of the stream is reached.
 214      *
 215      * @param       cbuf  Destination buffer
 216      *
 217      * @return      The number of characters read, or -1
 218      *              if the end of the stream
 219      *              has been reached
 220      *
 221      * @exception   IOException  If an I/O error occurs
 222      */
 223     public int read(char cbuf[]) throws IOException {
 224         return read(cbuf, 0, cbuf.length);
 225     }
 226 
 227     /**
 228      * Reads characters into a portion of an array.  This method will block
 229      * until some input is available, an I/O error occurs, or the end of the
 230      * stream is reached.
 231      *
 232      * @param      cbuf  Destination buffer
 233      * @param      off   Offset at which to start storing characters
 234      * @param      len   Maximum number of characters to read
 235      *
 236      * @return     The number of characters read, or -1 if the end of the
 237      *             stream has been reached
 238      *
 239      * @exception  IOException  If an I/O error occurs
 240      * @exception  IndexOutOfBoundsException
 241      *             If {@code off} is negative, or {@code len} is negative,
 242      *             or {@code len} is greater than {@code cbuf.length - off}
 243      */
 244     public abstract int read(char cbuf[], int off, int len) throws IOException;
 245 
 246     /** Maximum skip-buffer size */
 247     private static final int maxSkipBufferSize = 8192;
 248 
 249     /** Skip buffer, null until allocated */
 250     private char skipBuffer[] = null;
 251 
 252     /**
 253      * Skips characters.  This method will block until some characters are
 254      * available, an I/O error occurs, or the end of the stream is reached.
 255      *
 256      * @param  n  The number of characters to skip
 257      *
 258      * @return    The number of characters actually skipped
 259      *
 260      * @exception  IllegalArgumentException  If <code>n</code> is negative.
 261      * @exception  IOException  If an I/O error occurs
 262      */
 263     public long skip(long n) throws IOException {
 264         if (n < 0L)
 265             throw new IllegalArgumentException("skip value is negative");
 266         int nn = (int) Math.min(n, maxSkipBufferSize);
 267         synchronized (lock) {
 268             if ((skipBuffer == null) || (skipBuffer.length < nn))
 269                 skipBuffer = new char[nn];
 270             long r = n;
 271             while (r > 0) {
 272                 int nc = read(skipBuffer, 0, (int)Math.min(r, nn));
 273                 if (nc == -1)
 274                     break;
 275                 r -= nc;
 276             }
 277             return n - r;
 278         }
 279     }
 280 
 281     /**
 282      * Tells whether this stream is ready to be read.
 283      *
 284      * @return True if the next read() is guaranteed not to block for input,
 285      * false otherwise.  Note that returning false does not guarantee that the
 286      * next read will block.
 287      *
 288      * @exception  IOException  If an I/O error occurs
 289      */
 290     public boolean ready() throws IOException {
 291         return false;
 292     }
 293 
 294     /**
 295      * Tells whether this stream supports the mark() operation. The default
 296      * implementation always returns false. Subclasses should override this
 297      * method.
 298      *
 299      * @return true if and only if this stream supports the mark operation.
 300      */
 301     public boolean markSupported() {
 302         return false;
 303     }
 304 
 305     /**
 306      * Marks the present position in the stream.  Subsequent calls to reset()
 307      * will attempt to reposition the stream to this point.  Not all
 308      * character-input streams support the mark() operation.
 309      *
 310      * @param  readAheadLimit  Limit on the number of characters that may be
 311      *                         read while still preserving the mark.  After
 312      *                         reading this many characters, attempting to
 313      *                         reset the stream may fail.
 314      *
 315      * @exception  IOException  If the stream does not support mark(),
 316      *                          or if some other I/O error occurs
 317      */
 318     public void mark(int readAheadLimit) throws IOException {
 319         throw new IOException("mark() not supported");
 320     }
 321 
 322     /**
 323      * Resets the stream.  If the stream has been marked, then attempt to
 324      * reposition it at the mark.  If the stream has not been marked, then
 325      * attempt to reset it in some way appropriate to the particular stream,
 326      * for example by repositioning it to its starting point.  Not all
 327      * character-input streams support the reset() operation, and some support
 328      * reset() without supporting mark().
 329      *
 330      * @exception  IOException  If the stream has not been marked,
 331      *                          or if the mark has been invalidated,
 332      *                          or if the stream does not support reset(),
 333      *                          or if some other I/O error occurs
 334      */
 335     public void reset() throws IOException {
 336         throw new IOException("reset() not supported");
 337     }
 338 
 339     /**
 340      * Closes the stream and releases any system resources associated with
 341      * it.  Once the stream has been closed, further read(), ready(),
 342      * mark(), reset(), or skip() invocations will throw an IOException.
 343      * Closing a previously closed stream has no effect.
 344      *
 345      * @exception  IOException  If an I/O error occurs
 346      */
 347      public abstract void close() throws IOException;
 348 
 349     /**
 350      * Reads all characters from this reader and writes the characters to the
 351      * given writer in the order that they are read. On return, this reader
 352      * will be at end of the stream. This method does not close either reader
 353      * or writer.
 354      * <p>
 355      * This method may block indefinitely reading from the reader, or
 356      * writing to the writer. The behavior for the case where the reader
 357      * and/or writer is <i>asynchronously closed</i>, or the thread
 358      * interrupted during the transfer, is highly reader and writer
 359      * specific, and therefore not specified.
 360      * <p>
 361      * If an I/O error occurs reading from the reader or writing to the
 362      * writer, then it may do so after some characters have been read or
 363      * written. Consequently the reader may not be at end of the stream and
 364      * one, or both, streams may be in an inconsistent state. It is strongly
 365      * recommended that both streams be promptly closed if an I/O error occurs.
 366      *
 367      * @param  out the writer, non-null
 368      * @return the number of characters transferred
 369      * @throws IOException if an I/O error occurs when reading or writing
 370      * @throws NullPointerException if {@code out} is {@code null}
 371      *
 372      * @since 10
 373      */
 374     public long transferTo(Writer out) throws IOException {
 375         Objects.requireNonNull(out, "out");
 376         long transferred = 0;
 377         char[] buffer = new char[TRANSFER_BUFFER_SIZE];
 378         int nRead;
 379         while ((nRead = read(buffer, 0, TRANSFER_BUFFER_SIZE)) >= 0) {
 380             out.write(buffer, 0, nRead);
 381             transferred += nRead;
 382         }
 383         return transferred;
 384     }
 385 
 386 }