All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.atlan.util.StreamUtils Maven / Gradle / Ivy

There is a newer version: 3.0.0
Show newest version
// Generated by delombok at Wed Oct 16 22:16:02 UTC 2024
/* SPDX-License-Identifier: Apache-2.0
   Copyright 2022 Atlan Pte. Ltd. */
package com.atlan.util;

/* Based on original code from https://github.com/stripe/stripe-java (under MIT license) */
import static java.util.Objects.requireNonNull;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;

/**
 * Utilities for working with streams of data.
 */
public final class StreamUtils {
    private static final int DEFAULT_BUF_SIZE = 1024;

    /**
     * Reads the provided stream until the end and returns a string encoded with the provided charset.
     *
     * @param stream the stream to read
     * @param charset the charset to use
     * @return a string with the contents of the input stream
     * @throws NullPointerException if {@code stream} or {@code charset} is {@code null}
     * @throws IOException if an I/O error occurs
     */
    public static String readToEnd(InputStream stream, Charset charset) throws IOException {
        requireNonNull(stream);
        requireNonNull(charset);
        final StringBuilder sb = new StringBuilder();
        final char[] buffer = new char[DEFAULT_BUF_SIZE];
        final Reader in = new InputStreamReader(stream, charset);
        try {
            int charsRead = 0;
            while ((charsRead = in.read(buffer, 0, buffer.length)) > 0) {
                sb.append(buffer, 0, charsRead);
            }
            return sb.toString();
        } finally {
            if (java.util.Collections.singletonList(in).get(0) != null) {
                in.close();
            }
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy