简体   繁体   中英

Java BufferedInputStream Progress Bar

I'm having a slight issue getting a JProgressBar to show the status of an HTTP download.
The progress bar is working, however it fills up too quickly and eventually overshoots the max value by quite an amount, as shown below:

public void test(InputStream stream, File location) {  
    BufferedInputStream in = new BufferedInputStream(stream);  
    FileOutputStream file = new FileOutputStream(location);  
    BufferedOutputStream out = new BufferedOutputStream(file);  
    int i;  
    int bytesDownloaded = 0;  
    while ((i = in.read()) != -1) {  
        bytesDownloaded += i;  
        out.write(i);  
        System.out.println("Bytes downloaded: " + bytesDownloaded + " out of " + len);  
        update(bytesDownloaded);  
    }
}

The issue is that bytesDownloaded ends up being much greater than len at the end of the file, is in.read() actually returning the bytes it's upto in the file or some other value? I'm assuming the former from the Java 7 API, however it does not line up with my findings.

I am testing this snippet on a 2.69MB File.
This is the output from the println statement (the last few lines)

Bytes downloaded: 371525502 out of 2821490
Bytes downloaded: 371525526 out of 2821490
Bytes downloaded: 371525631 out of 2821490
Bytes downloaded: 371525788 out of 2821490
Bytes downloaded: 371526028 out of 2821490
Bytes downloaded: 371526222 out of 2821490
Bytes downloaded: 371526442 out of 2821490
Bytes downloaded: 371526697 out of 2821490
Bytes downloaded: 371526914 out of 2821490

Now I know that 2821490 is the correct byte value of 2.69MB, so then my question remains, why is the read() function of the BufferedInputStream showing the end of file read bytes as 371526914 , if this really was bytes then that equals around 350MB which the file is obviously not!

Any ideas?

I worked it out, after i = in.read() executes the i variable holds the byte representation of the data one byte into the file, and so on for each loop iteration. So it is not a count of bytes read, it is the actual data of one byte.

I changed my bytesDownloaded += i; to bytesDownloaded++; and that gave me the correct result both in the debug output as well as the progress bar.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM