Java InputStream to String inputStreamToString(final InputStream stream)

Here you can find the source of inputStreamToString(final InputStream stream)

Description

Derived from the Jrubyrack project - IOHelpers

License

Open Source License

Declaration

public static String inputStreamToString(final InputStream stream) throws IOException 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    /**//w ww . jav  a 2 s.  co  m
     * Derived from the Jrubyrack project - IOHelpers
     * @author kares 
     */
    public static String inputStreamToString(final InputStream stream) throws IOException {
        if (stream == null)
            return null;

        final StringBuilder str = new StringBuilder(128);
        String coding = "UTF-8";
        int c = stream.read();
        if (c == '#') { // look for a coding: pragma
            str.append((char) c);
            while ((c = stream.read()) != -1 && c != 10) {
                str.append((char) c);
            }
            Pattern pattern = Pattern.compile("coding:\\s*(\\S+)");
            Matcher matcher = pattern.matcher(str.toString());
            if (matcher.find()) {
                coding = matcher.group(1);
            }
        }

        str.append((char) c);
        Reader reader = new InputStreamReader(stream, coding);

        while ((c = reader.read()) != -1) {
            str.append((char) c);
        }

        return str.toString();
    }
}

Related

  1. inputStreamToReaderToString(InputStream in)
  2. inputStreamtoStream(InputStream in)
  3. inputStreamToString(final InputStream in)
  4. inputStreamToString(final InputStream inputStream, final String... optionalCharsetName)
  5. inputStreamToString(final InputStream is, final int bufferSize)
  6. inputStreamToString(final InputStream stream, final String charset)
  7. inputStreamToString(InputStream in)
  8. inputStreamToString(InputStream in)
  9. inputStreamToString(InputStream in)