Java InputStream Read by Charset inputStreamToString(InputStream inputStream, String charset)

Here you can find the source of inputStreamToString(InputStream inputStream, String charset)

Description

input Stream To String

License

Apache License

Declaration

public static String inputStreamToString(InputStream inputStream, String charset) throws IOException 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import java.nio.charset.Charset;

public class Main {
    public static String inputStreamToString(InputStream inputStream) throws IOException {
        return inputStreamToString(inputStream, Charset.forName("UTF-8"));
    }//from   w w  w. ja  va2 s .c  o m

    public static String inputStreamToString(InputStream inputStream, String charset) throws IOException {
        return inputStreamToString(inputStream, Charset.forName(charset));
    }

    /**
     * Retrieves all data for given {@link java.io.InputStream} as String.
     *
     * @param inputStream {@link java.io.InputStream} to process.
     * @param charset {@link java.nio.charset.Charset} to be used during byte to string conversion.
     * @return string representation of {@link java.io.InputStream} data.
     * @throws IOException  If the first byte cannot be read for any reason
     *      other than the end of the file, if the input stream has been closed, or
     *      if some other I/O error occurs.
     */
    public static String inputStreamToString(InputStream inputStream, Charset charset) throws IOException {
        if (inputStream == null) {
            return null;
        }
        try (ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream()) {
            byte[] buffer = new byte[1024];
            int length;
            while ((length = inputStream.read(buffer)) != -1) {
                arrayOutputStream.write(buffer, 0, length);
            }
            return arrayOutputStream.toString(charset.name());
        }
    }
}

Related

  1. input2String(InputStream input, Charset encoding)
  2. inputStreamAsString(InputStream stream, Charset cs)
  3. inputStreamToString(final InputStream inputStream, final String charsetName)
  4. inputstreamToString(InputStream input, CharsetDecoder decoder)
  5. inputStreamToString(InputStream inputStream, Charset charset)
  6. inputStreamToString(InputStream is, Charset charset)
  7. isCharsetMisInterpreted(String input, String encoding)
  8. lines(InputStream in, Charset cs)
  9. loadInputStream(InputStream in, Charset cs)