summaryrefslogtreecommitdiff
path: root/src/main/java/org/zwobble/mammoth/internal/util/Streams.java
blob: 69cd79609cbbffed4e1be848626ea292048b9081 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package org.zwobble.mammoth.internal.util;

import java.io.*;
import java.util.stream.Collectors;

public class Streams {
    private Streams() {}

    public static void copy(InputStream source, OutputStream destination) throws IOException {
        byte[] buffer = new byte[4096];
        while (true) {
            int bytesRead = source.read(buffer);
            if (bytesRead == -1) {
                return;
            }
            destination.write(buffer, 0, bytesRead);
        }
    }

    public static byte[] toByteArray(InputStream stream) throws IOException {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        copy(stream, output);
        return output.toByteArray();
    }

    public static String toString(InputStream stream) {
        return new BufferedReader(new InputStreamReader(stream))
            .lines()
            .collect(Collectors.joining("\n"));
    }
}