01: /* ====================================================================
02: Licensed to the Apache Software Foundation (ASF) under one or more
03: contributor license agreements. See the NOTICE file distributed with
04: this work for additional information regarding copyright ownership.
05: The ASF licenses this file to You under the Apache License, Version 2.0
06: (the "License"); you may not use this file except in compliance with
07: the License. You may obtain a copy of the License at
08:
09: http://www.apache.org/licenses/LICENSE-2.0
10:
11: Unless required by applicable law or agreed to in writing, software
12: distributed under the License is distributed on an "AS IS" BASIS,
13: WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14: See the License for the specific language governing permissions and
15: limitations under the License.
16: ==================================================================== */
17:
18: package org.apache.poi.util;
19:
20: import java.io.ByteArrayOutputStream;
21: import java.io.IOException;
22: import java.io.InputStream;
23:
24: public class IOUtils {
25: private IOUtils() {
26: }
27:
28: /**
29: * Reads all the data from the input stream, and returns
30: * the bytes read.
31: */
32: public static byte[] toByteArray(InputStream stream)
33: throws IOException {
34: ByteArrayOutputStream baos = new ByteArrayOutputStream();
35:
36: byte[] buffer = new byte[4096];
37: int read = 0;
38: while (read != -1) {
39: read = stream.read(buffer);
40: if (read > 0) {
41: baos.write(buffer, 0, read);
42: }
43: }
44:
45: return baos.toByteArray();
46: }
47:
48: /**
49: * Helper method, just calls <tt>readFully(in, b, 0, b.length)</tt>
50: */
51: public static int readFully(InputStream in, byte[] b)
52: throws IOException {
53: return readFully(in, b, 0, b.length);
54: }
55:
56: /**
57: * Same as the normal <tt>in.read(b, off, len)</tt>, but tries to ensure that
58: * the entire len number of bytes is read.
59: * <p>
60: * If the end of file is reached before any bytes are read, returns -1.
61: * Otherwise, returns the number of bytes read.
62: */
63: public static int readFully(InputStream in, byte[] b, int off,
64: int len) throws IOException {
65: int total = 0;
66: for (;;) {
67: int got = in.read(b, off + total, len - total);
68: if (got < 0) {
69: return (total == 0) ? -1 : total;
70: } else {
71: total += got;
72: if (total == len)
73: return total;
74: }
75: }
76: }
77: }
|