14
14
15
15
package com .google .api .client .util ;
16
16
17
- import static com .google .common .base .Preconditions .checkNotNull ;
18
-
19
17
import java .io .FilterInputStream ;
20
18
import java .io .IOException ;
21
19
import java .io .InputStream ;
@@ -42,11 +40,10 @@ public final class ByteStreams {
42
40
* @param from the input stream to read from
43
41
* @param to the output stream to write to
44
42
* @return the number of bytes copied
45
- * @throws IOException if an I/O error occurs
46
43
*/
47
44
public static long copy (InputStream from , OutputStream to ) throws IOException {
48
- checkNotNull (from );
49
- checkNotNull (to );
45
+ Preconditions . checkNotNull (from );
46
+ Preconditions . checkNotNull (to );
50
47
byte [] buf = new byte [BUF_SIZE ];
51
48
long total = 0 ;
52
49
while (true ) {
@@ -144,6 +141,51 @@ public long skip(long n) throws IOException {
144
141
}
145
142
}
146
143
144
+ /**
145
+ * Reads some bytes from an input stream and stores them into the buffer array {@code b}.
146
+ *
147
+ * <p>
148
+ * This method blocks until {@code len} bytes of input data have been read into the array, or end
149
+ * of file is detected. The number of bytes read is returned, possibly zero. Does not close the
150
+ * stream.
151
+ * </p>
152
+ *
153
+ * <p>
154
+ * A caller can detect EOF if the number of bytes read is less than {@code len}. All subsequent
155
+ * calls on the same stream will return zero.
156
+ * </p>
157
+ *
158
+ * <p>
159
+ * If {@code b} is null, a {@code NullPointerException} is thrown. If {@code off} is negative, or
160
+ * {@code len} is negative, or {@code off+len} is greater than the length of the array {@code b},
161
+ * then an {@code IndexOutOfBoundsException} is thrown. If {@code len} is zero, then no bytes are
162
+ * read. Otherwise, the first byte read is stored into element {@code b[off]}, the next one into
163
+ * {@code b[off+1]}, and so on. The number of bytes read is, at most, equal to {@code len}.
164
+ * </p>
165
+ *
166
+ * @param in the input stream to read from
167
+ * @param b the buffer into which the data is read
168
+ * @param off an int specifying the offset into the data
169
+ * @param len an int specifying the number of bytes to read
170
+ * @return the number of bytes read
171
+ */
172
+ public static int read (InputStream in , byte [] b , int off , int len ) throws IOException {
173
+ Preconditions .checkNotNull (in );
174
+ Preconditions .checkNotNull (b );
175
+ if (len < 0 ) {
176
+ throw new IndexOutOfBoundsException ("len is negative" );
177
+ }
178
+ int total = 0 ;
179
+ while (total < len ) {
180
+ int result = in .read (b , off + total , len - total );
181
+ if (result == -1 ) {
182
+ break ;
183
+ }
184
+ total += result ;
185
+ }
186
+ return total ;
187
+ }
188
+
147
189
private ByteStreams () {
148
190
}
149
191
}
0 commit comments