Eric Martin Eric Martin - 1 month ago 7x
Java Question

Get loading percent from InputStream .read method

I have a problem in parsing an InputStream and getting the loading percentage of his data. I mean, my method needs to parse the InputStream, put it into a StringBuffer, get the total of bytes parsed and returns a String based on my StringBuffer.

private String processPercent(InputStream content, HttpResponse response) throws IOException
InputStream in = content;
int totalBytes = Integer.parseInt(response.getFirstHeader("Content-Length").getValue());
int processedByte;
int loaded = 0;
StringBuffer sb = new StringBuffer();

while((processedByte = != -1)

sb.append((char) processedByte);

if(this.asyncTask instanceof IProgressPercent)
lastProcessed = processedByte;
loaded += processedByte;
float percent = ((100*loaded) / totalBytes);
this.progressPercent = (int)percent;


return new String(sb);

The problem is when I display the value of percent variable, I get a value higher than 100, so I think that's a calculation problem.

Any idea ? Thanks.



    loaded += processedByte;



before the if actually; incrementing by 1.