Java InputStream Read by Charset toString(InputStream source, Charset charset)

Here you can find the source of toString(InputStream source, Charset charset)

Description

to String

License

Mozilla Public License

Declaration

static String toString(InputStream source, Charset charset) throws IOException 

Method Source Code


//package com.java2s;
/*/*from ww w  .  j a v  a  2 s . c o m*/
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

import java.io.*;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

public class Main {
    static String toString(InputStream source) throws IOException {
        return toString(source, StandardCharsets.UTF_8);
    }

    static String toString(InputStream source, Charset charset) throws IOException {
        try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            copy(source, out);
            return new String(out.toByteArray(), charset);
        }
    }

    static void copy(InputStream source, OutputStream out) throws IOException {
        for (int read = source.read(); read != -1; read = source.read()) {
            out.write(read);
        }
        out.flush();
    }

    static void copy(InputStream source, OutputStream... out) throws IOException {
        for (int read = source.read(); read != -1; read = source.read()) {
            for (OutputStream i : out) {
                i.write(read);
            }
        }

        for (OutputStream i : out) {
            i.flush();
        }
    }

    static void read(InputStream source) throws IOException {
        for (int read = source.read(); read != -1; read = source.read()) {
        }
    }
}

Related

  1. toString(InputStream input, Charset charset)
  2. toString(InputStream input, String charset)
  3. toString(InputStream inputStream, Charset charset)
  4. toString(InputStream is, Charset charset)
  5. toString(InputStream is, String charset)
  6. toString(InputStream stream, Charset chs)
  7. tryParseString(InputStream is, String... charsets)