Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not getting whole data while using available()

I m not getting the whole data sometimes while reading the inputStream like this(somtime full data is recieved).

 private String readInputStream(InputStream in) {
            PushbackInputStream inputStream = (PushbackInputStream) in;
            StringBuffer outputBuffer = null;
            try {
                int size = inputStream.available();
                    outputBuffer = new StringBuffer(size);
                    // append the data into the stringBuilder
                    for (int j = 0; j < size; j++) {
                        int ch = inputStream.read();
                        outputBuffer.append((char) ch);
                    }
            } catch (IOException ioe) {
                Log.e("error", "IOException: " +
                        ioe.getMessage());
            }
            if (outputBuffer != null) {
                return outputBuffer.toString();
        }

should i read the input Stream until inputStream.available() is zero..?Data in inputStream is large.Plz Suggest some altenative with Sample code

like image 981
Manas Pratim Chamuah Avatar asked Nov 11 '22 04:11

Manas Pratim Chamuah


1 Answers

You're misusing available(). See the Javadoc. It isn't anything to do with 'size', only with what can currently be read without blocking. And that can be as little as zero bytes.

You should read until end of stream, or until you have a complete message, or line, or document, or whatever it is you're reading.

And as you're not making any use of the PushbackInputStream in this code, it is irrelevant to the problem.

like image 71
user207421 Avatar answered Nov 14 '22 21:11

user207421