BufferedInputStream.java 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. /* BufferedInputStream.java -- An input stream that implements buffering
  2. Copyright (C) 1998, 1999, 2001, 2005 Free Software Foundation, Inc.
  3. This file is part of GNU Classpath.
  4. GNU Classpath is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2, or (at your option)
  7. any later version.
  8. GNU Classpath is distributed in the hope that it will be useful, but
  9. WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with GNU Classpath; see the file COPYING. If not, write to the
  14. Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  15. 02110-1301 USA.
  16. Linking this library statically or dynamically with other modules is
  17. making a combined work based on this library. Thus, the terms and
  18. conditions of the GNU General Public License cover the whole
  19. combination.
  20. As a special exception, the copyright holders of this library give you
  21. permission to link this library with independent modules to produce an
  22. executable, regardless of the license terms of these independent
  23. modules, and to copy and distribute the resulting executable under
  24. terms of your choice, provided that you also meet, for each linked
  25. independent module, the terms and conditions of the license of that
  26. module. An independent module is a module which is not derived from
  27. or based on this library. If you modify this library, you may extend
  28. this exception to your version of the library, but you are not
  29. obligated to do so. If you do not wish to do so, delete this
  30. exception statement from your version. */
  31. package java.io;
  32. /* Written using "Java Class Libraries", 2nd edition, ISBN 0-201-31002-3
  33. * "The Java Language Specification", ISBN 0-201-63451-1
  34. * plus online API docs for JDK 1.2 beta from http://www.javasoft.com.
  35. * Status: Believed complete and correct.
  36. */
  37. /**
  38. * This subclass of <code>FilterInputStream</code> buffers input from an
  39. * underlying implementation to provide a possibly more efficient read
  40. * mechanism. It maintains the buffer and buffer state in instance
  41. * variables that are available to subclasses. The default buffer size
  42. * of 2048 bytes can be overridden by the creator of the stream.
  43. * <p>
  44. * This class also implements mark/reset functionality. It is capable
  45. * of remembering any number of input bytes, to the limits of
  46. * system memory or the size of <code>Integer.MAX_VALUE</code>
  47. * <p>
  48. * Please note that this class does not properly handle character
  49. * encodings. Consider using the <code>BufferedReader</code> class which
  50. * does.
  51. *
  52. * @author Aaron M. Renn (arenn@urbanophile.com)
  53. * @author Warren Levy (warrenl@cygnus.com)
  54. * @author Jeroen Frijters (jeroen@frijters.net)
  55. */
  56. public class BufferedInputStream extends FilterInputStream
  57. {
  58. /**
  59. * This is the default buffer size
  60. */
  61. private static final int DEFAULT_BUFFER_SIZE = 2048;
  62. /**
  63. * The buffer used for storing data from the underlying stream.
  64. */
  65. protected byte[] buf;
  66. /**
  67. * The number of valid bytes currently in the buffer. It is also the index
  68. * of the buffer position one byte past the end of the valid data.
  69. */
  70. protected int count;
  71. /**
  72. * The index of the next character that will by read from the buffer.
  73. * When <code>pos == count</code>, the buffer is empty.
  74. */
  75. protected int pos;
  76. /**
  77. * The value of <code>pos</code> when the <code>mark()</code> method was
  78. * called.
  79. * This is set to -1 if there is no mark set.
  80. */
  81. protected int markpos = -1;
  82. /**
  83. * This is the maximum number of bytes than can be read after a
  84. * call to <code>mark()</code> before the mark can be discarded.
  85. * After this may bytes are read, the <code>reset()</code> method
  86. * may not be called successfully.
  87. */
  88. protected int marklimit;
  89. /**
  90. * This is the initial buffer size. When the buffer is grown because
  91. * of marking requirements, it will be grown by bufferSize increments.
  92. * The underlying stream will be read in chunks of bufferSize.
  93. */
  94. private final int bufferSize;
  95. /**
  96. * This method initializes a new <code>BufferedInputStream</code> that will
  97. * read from the specified subordinate stream with a default buffer size
  98. * of 2048 bytes
  99. *
  100. * @param in The subordinate stream to read from
  101. */
  102. public BufferedInputStream(InputStream in)
  103. {
  104. this(in, DEFAULT_BUFFER_SIZE);
  105. }
  106. /**
  107. * This method initializes a new <code>BufferedInputStream</code> that will
  108. * read from the specified subordinate stream with a buffer size that
  109. * is specified by the caller.
  110. *
  111. * @param in The subordinate stream to read from
  112. * @param size The buffer size to use
  113. *
  114. * @exception IllegalArgumentException when size is smaller then 1
  115. */
  116. public BufferedInputStream(InputStream in, int size)
  117. {
  118. super(in);
  119. if (size <= 0)
  120. throw new IllegalArgumentException();
  121. buf = new byte[size];
  122. // initialize pos & count to bufferSize, to prevent refill from
  123. // allocating a new buffer (if the caller starts out by calling mark()).
  124. pos = count = bufferSize = size;
  125. }
  126. /**
  127. * This method returns the number of bytes that can be read from this
  128. * stream before a read can block. A return of 0 indicates that blocking
  129. * might (or might not) occur on the very next read attempt.
  130. * <p>
  131. * The number of available bytes will be the number of read ahead bytes
  132. * stored in the internal buffer plus the number of available bytes in
  133. * the underlying stream.
  134. *
  135. * @return The number of bytes that can be read before blocking could occur
  136. *
  137. * @exception IOException If an error occurs
  138. */
  139. public synchronized int available() throws IOException
  140. {
  141. return count - pos + super.available();
  142. }
  143. /**
  144. * This method closes the underlying input stream and frees any
  145. * resources associated with it. Sets <code>buf</code> to <code>null</code>.
  146. *
  147. * @exception IOException If an error occurs.
  148. */
  149. public void close() throws IOException
  150. {
  151. // Free up the array memory.
  152. buf = null;
  153. pos = count = 0;
  154. markpos = -1;
  155. super.close();
  156. }
  157. /**
  158. * This method marks a position in the input to which the stream can be
  159. * "reset" by calling the <code>reset()</code> method. The parameter
  160. * <code>readlimit</code> is the number of bytes that can be read from the
  161. * stream after setting the mark before the mark becomes invalid. For
  162. * example, if <code>mark()</code> is called with a read limit of 10, then
  163. * when 11 bytes of data are read from the stream before the
  164. * <code>reset()</code> method is called, then the mark is invalid and the
  165. * stream object instance is not required to remember the mark.
  166. * <p>
  167. * Note that the number of bytes that can be remembered by this method
  168. * can be greater than the size of the internal read buffer. It is also
  169. * not dependent on the subordinate stream supporting mark/reset
  170. * functionality.
  171. *
  172. * @param readlimit The number of bytes that can be read before the mark
  173. * becomes invalid
  174. */
  175. public synchronized void mark(int readlimit)
  176. {
  177. marklimit = readlimit;
  178. markpos = pos;
  179. }
  180. /**
  181. * This method returns <code>true</code> to indicate that this class
  182. * supports mark/reset functionality.
  183. *
  184. * @return <code>true</code> to indicate that mark/reset functionality is
  185. * supported
  186. *
  187. */
  188. public boolean markSupported()
  189. {
  190. return true;
  191. }
  192. /**
  193. * This method reads an unsigned byte from the input stream and returns it
  194. * as an int in the range of 0-255. This method also will return -1 if
  195. * the end of the stream has been reached.
  196. * <p>
  197. * This method will block until the byte can be read.
  198. *
  199. * @return The byte read or -1 if end of stream
  200. *
  201. * @exception IOException If an error occurs
  202. */
  203. public synchronized int read() throws IOException
  204. {
  205. if (pos >= count && !refill())
  206. return -1; // EOF
  207. return buf[pos++] & 0xFF;
  208. }
  209. /**
  210. * This method reads bytes from a stream and stores them into a caller
  211. * supplied buffer. It starts storing the data at index <code>off</code>
  212. * into the buffer and attempts to read <code>len</code> bytes. This method
  213. * can return before reading the number of bytes requested, but it will try
  214. * to read the requested number of bytes by repeatedly calling the underlying
  215. * stream as long as available() for this stream continues to return a
  216. * non-zero value (or until the requested number of bytes have been read).
  217. * The actual number of bytes read is returned as an int. A -1 is returned
  218. * to indicate the end of the stream.
  219. * <p>
  220. * This method will block until some data can be read.
  221. *
  222. * @param b The array into which the bytes read should be stored
  223. * @param off The offset into the array to start storing bytes
  224. * @param len The requested number of bytes to read
  225. *
  226. * @return The actual number of bytes read, or -1 if end of stream.
  227. *
  228. * @exception IOException If an error occurs.
  229. * @exception IndexOutOfBoundsException when <code>off</code> or
  230. * <code>len</code> are negative, or when <code>off + len</code>
  231. * is larger then the size of <code>b</code>,
  232. */
  233. public synchronized int read(byte[] b, int off, int len) throws IOException
  234. {
  235. if (off < 0 || len < 0 || b.length - off < len)
  236. throw new IndexOutOfBoundsException();
  237. if (len == 0)
  238. return 0;
  239. if (pos >= count && !refill())
  240. return -1; // No bytes were read before EOF.
  241. int totalBytesRead = Math.min(count - pos, len);
  242. System.arraycopy(buf, pos, b, off, totalBytesRead);
  243. pos += totalBytesRead;
  244. off += totalBytesRead;
  245. len -= totalBytesRead;
  246. while (len > 0 && super.available() > 0 && refill())
  247. {
  248. int remain = Math.min(count - pos, len);
  249. System.arraycopy(buf, pos, b, off, remain);
  250. pos += remain;
  251. off += remain;
  252. len -= remain;
  253. totalBytesRead += remain;
  254. }
  255. return totalBytesRead;
  256. }
  257. /**
  258. * This method resets a stream to the point where the <code>mark()</code>
  259. * method was called. Any bytes that were read after the mark point was
  260. * set will be re-read during subsequent reads.
  261. * <p>
  262. * This method will throw an IOException if the number of bytes read from
  263. * the stream since the call to <code>mark()</code> exceeds the mark limit
  264. * passed when establishing the mark.
  265. *
  266. * @exception IOException If <code>mark()</code> was never called or more
  267. * then <code>marklimit</code> bytes were read since the last
  268. * call to <code>mark()</code>
  269. */
  270. public synchronized void reset() throws IOException
  271. {
  272. if (markpos == -1)
  273. throw new IOException(buf == null ? "Stream closed." : "Invalid mark.");
  274. pos = markpos;
  275. }
  276. /**
  277. * This method skips the specified number of bytes in the stream. It
  278. * returns the actual number of bytes skipped, which may be less than the
  279. * requested amount.
  280. *
  281. * @param n The requested number of bytes to skip
  282. *
  283. * @return The actual number of bytes skipped.
  284. *
  285. * @exception IOException If an error occurs
  286. */
  287. public synchronized long skip(long n) throws IOException
  288. {
  289. if (buf == null)
  290. throw new IOException("Stream closed.");
  291. final long origN = n;
  292. while (n > 0L)
  293. {
  294. if (pos >= count && !refill())
  295. break;
  296. int numread = (int) Math.min((long) (count - pos), n);
  297. pos += numread;
  298. n -= numread;
  299. }
  300. return origN - n;
  301. }
  302. /**
  303. * Called to refill the buffer (when count is equal to pos).
  304. *
  305. * @return <code>true</code> when at least one additional byte was read
  306. * into <code>buf</code>, <code>false</code> otherwise (at EOF).
  307. */
  308. private boolean refill() throws IOException
  309. {
  310. if (buf == null)
  311. throw new IOException("Stream closed.");
  312. if (markpos == -1 || count - markpos >= marklimit)
  313. {
  314. markpos = -1;
  315. pos = count = 0;
  316. }
  317. else
  318. {
  319. byte[] newbuf = buf;
  320. if (markpos < bufferSize)
  321. {
  322. newbuf = new byte[count - markpos + bufferSize];
  323. }
  324. System.arraycopy(buf, markpos, newbuf, 0, count - markpos);
  325. buf = newbuf;
  326. count -= markpos;
  327. pos -= markpos;
  328. markpos = 0;
  329. }
  330. int numread = super.read(buf, count, bufferSize);
  331. if (numread <= 0) // EOF
  332. return false;
  333. count += numread;
  334. return true;
  335. }
  336. }