Eric Martin Eric Martin - 2 months ago 9
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 = in.read()) != -1)
{

sb.append((char) processedByte);

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

in.close();

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.

Answer

Replace

    loaded += processedByte;

with

++loaded;

before the if actually; incrementing by 1.

Comments