Convert InputStream to String with the encoding specified in the stream data

My input is an InputStream that contains an XML document. The encoding used in XML is unknown and is defined in the first line of the XML document. From this InputStream, I want to have the entire document in String.

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

This does not seem to be the best way to achieve this, as it is causing an OutOfMemory error.

Any idea how to do this?

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;
}
+3
source share
2 answers

mark(Integer.MAX_VALUE) OutOfMemoryError, 2 .

, . readLimit , 8K. 99% , , 16K , . , , , , , readLimit.

, InputStream , , . ByteArrayInputStream InputStreamReader, "readerForEncoding".

+2

. ...

private String convertStreamToString(InputStream input) throws Exception{
    BufferedReader reader = new BufferedReader(new InputStreamReader(input));
    StringBuilder sb = new StringBuilder();
    String line = null;

    while ((line = reader.readLine()) != null) {
        sb.append(line);
    }

    input.close();
    return sb.toString();
}
0

Source: https://habr.com/ru/post/1746382/


All Articles