1/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package libcore.io;
18
19import java.io.ByteArrayOutputStream;
20import java.io.IOException;
21import java.io.InputStream;
22import java.io.OutputStream;
23
24public final class Streams {
25    private Streams() {}
26
27    /**
28     * Returns a byte[] containing the remainder of 'in', closing it when done.
29     */
30    public static byte[] readFully(InputStream in) throws IOException {
31        try {
32            return readFullyNoClose(in);
33        } finally {
34            in.close();
35        }
36    }
37
38    /**
39     * Returns a byte[] containing the remainder of 'in'.
40     */
41    private static byte[] readFullyNoClose(InputStream in) throws IOException {
42        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
43        byte[] buffer = new byte[1024];
44        int count;
45        while ((count = in.read(buffer)) != -1) {
46            bytes.write(buffer, 0, count);
47        }
48        return bytes.toByteArray();
49    }
50
51    /**
52     * Copies all of the bytes from {@code in} to {@code out}. Neither stream is closed.
53     * Returns the total number of bytes transferred.
54     */
55    public static int copy(InputStream in, OutputStream out) throws IOException {
56        int total = 0;
57        byte[] buffer = new byte[8192];
58        int c;
59        while ((c = in.read(buffer)) != -1) {
60            total += c;
61            out.write(buffer, 0, c);
62        }
63        return total;
64    }
65}
66