Convert InputStream to String with encoding given in stream data

Posted by Quentin on Stack Overflow See other posts from Stack Overflow or by Quentin
Published on 2010-05-20T13:07:07Z Indexed on 2010/05/20 13:10 UTC
Read the original article Hit count: 251

Filed under:
|

Hi,

My input is a InputStream which contains an XML document. Encoding used in XML is unknown and it is defined in the first line of XML document. From this InputStream, I want to have all document in a String.

To do this, I use a BufferedInputStream to mark the beginning of the file and start reading first line. I read this first line to get encoding and then I use an InputStreamReader to generate a String with the correct encoding.

It seems that it is not the best way to achieve this goal because it produces an OutOfMemory error.

Any idea, how to do it ?

    public static String streamToString(final InputStream is) {
    String result = null;
    if (is != null) {
        BufferedInputStream bis = new BufferedInputStream(is);
        bis.mark(Integer.MAX_VALUE);
        final StringBuilder stringBuilder = new StringBuilder();
        try {
            // stream reader that handle encoding
            final InputStreamReader readerForEncoding = new InputStreamReader(bis, "UTF-8");
            final BufferedReader bufferedReaderForEncoding = new BufferedReader(readerForEncoding);

            String encoding = extractEncodingFromStream(bufferedReaderForEncoding);
            if (encoding == null) {
                encoding = DEFAULT_ENCODING;
            }

            // stream reader that handle encoding
            bis.reset();
            final InputStreamReader readerForContent = new InputStreamReader(bis, encoding);
            final BufferedReader bufferedReaderForContent = new BufferedReader(readerForContent);

            String line = bufferedReaderForContent.readLine();
            while (line != null) {
                stringBuilder.append(line); 
                line  = bufferedReaderForContent.readLine();
            } 
            bufferedReaderForContent.close();
            bufferedReaderForEncoding.close();
        } catch (IOException e) { 
            // reset string builder
            stringBuilder.delete(0, stringBuilder.length());
        }  
        result = stringBuilder.toString();
    }else {
        result = null;
    }
    return result;
}

Regards, Quentin

© Stack Overflow or respective owner

Related posts about android

Related posts about java