Java InputStream Copy copyStreamToString(InputStream inputStream, String encoding)

Here you can find the source of copyStreamToString(InputStream inputStream, String encoding)

Description

Copies data from the input stream and returns a String (UTF-8 if not specified)

License

BSD License

Declaration

public static String copyStreamToString(InputStream inputStream, String encoding) throws IOException 

Method Source Code


//package com.java2s;
// BSD License (http://lemurproject.org/galago-license)

import java.io.*;

public class Main {
    /**// www . j a va2s.c  om
     * Copies data from the input stream and returns a String (UTF-8 if not specified)
     */
    public static String copyStreamToString(InputStream inputStream, String encoding) throws IOException {
        encoding = (encoding == null) ? "UTF-8" : encoding;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        copyStream(inputStream, baos);
        return baos.toString(encoding);
    }

    public static String copyStreamToString(InputStream input) throws IOException {
        return copyStreamToString(input, "UTF-8");
    }

    /**
     * Copies data from the input stream to the output stream.
     *
     * @param input The input stream.
     * @param output The output stream.
     * @throws java.io.IOException
     */
    public static void copyStream(InputStream input, OutputStream output) throws IOException {
        byte[] data = new byte[65536];
        while (true) {
            int bytesRead = input.read(data);
            if (bytesRead < 0) {
                break;
            }
            output.write(data, 0, bytesRead);
        }
    }
}

Related

  1. copyStreamToByteArray(InputStream in, byte[] dest, int off, int len)
  2. copyStreamToBytes(InputStream inputStream)
  3. copyStreamToString(InputStream input)
  4. copyStreamToString(InputStream input)
  5. copyStreamToString(InputStream input)
  6. copyStreamToWriter(InputStream in, Writer out, String encoding, boolean close)
  7. copyStreamToWriter(InputStream inStream, Writer writer)