3

There are many posts on JProgressBar, but I can not find a solution for the following problem. How do I update JProgressBar measuring bytes received from InputStream?

For example, I have the following code:

int bytesRead;
byte buffer = new byte[1024];
ByteArrayOutputStream getBytes = new ByteArrayOutputStream();

while ((bytesRead = dis.read(buffer)) != -1) {
    getBytes.write(buffer, 0, bytesRead);
}

return(getBytes.toByteArray());
Sastrija
  • 3,284
  • 6
  • 47
  • 64
jadrijan
  • 1,438
  • 4
  • 31
  • 48
  • Where do you read your data from (file, HTTP, ..)? In some cases the used InputStream instance implements the **available()** method. – Robert Nov 27 '11 at 18:40
  • I am reading data through HTTP. available() method would be good for measurement if it returned the real number of bytes available to read, but as far as I know it does not do that. – jadrijan Nov 28 '11 at 13:31

2 Answers2

2

If you know how many bytes you will be reading, you can set that as the max and increment the progress bar by the number of bytes read for each iteration of the loop.

If you don't know how many bytes you will read, set the progress bar to indeterminate mode and it will animate itself showing that "some" progress is occurring.

unholysampler
  • 17,141
  • 7
  • 47
  • 64
1

If you know the total data size in your stream then you can do the following:

int nBytesReceived = 0;
int nTotalBytesInStream = ... // Total data size
progressBar.setMaximum(100) ;
progressBar.setMinimum(0) ;
while ((bytesRead = dis.read(buffer)) != -1) {
    getBytes.write(buffer, 0, bytesRead);
    nBytesReceived += bytesRead;
    progressBar.setValue(nBytesReceived*100/nTotalBytesInStream);
}

Make sure nTotalBytesInStream is not 0

This SO question might help you figure out the inputStream size

Community
  • 1
  • 1
GETah
  • 20,922
  • 7
  • 61
  • 103