Java InputStream Read by Charset collectStream(InputStream stream, Charset charset)

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

Description

Gets the contents of the InputStream as a String of given Charset.

License

Apache License

Parameter

Parameter Description
stream to read.
charset to use to decode characters.

Exception

Parameter Description
IOException if the stream can't be read.

Return

a String

Declaration

public static String collectStream(InputStream stream, Charset charset) throws IOException 

Method Source Code


//package com.java2s;
/*/*  ww w  .jav  a 2  s  . c o  m*/
 * Copyright 2015 to CloudModelExplorer authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;

public class Main {
    /**
     * Gets the contents of the InputStream as a String of given Charset.
     *
     * @param stream to read.
     * @param charset to use to decode characters.
     * @return a String
     * @throws IOException if the stream can't be read.
     */
    public static String collectStream(InputStream stream, Charset charset) throws IOException {
        StringBuilder textBuilder = new StringBuilder();
        try (Reader reader = new BufferedReader(new InputStreamReader(stream, charset))) {
            int c = reader.read();
            while (c != -1) {
                textBuilder.append((char) c);
                c = reader.read();
            }
        }
        return textBuilder.toString();
    }
}

Related

  1. asString(final InputStream is, Charset charset)
  2. consume(InputStream stream, Charset encoding)
  3. convertEncoding(Charset output_charset, String input_string)
  4. convertFromUnicode(String input, String targetCharset)
  5. convertStreamToString(final InputStream is, final Charset charset)