Java Progress Bar Help
-
27-10-2019 - |
Question
I need to implement a progress bar for the following task delay
FileOutputStream Fos= new FileOutputStream(FilePath);
byte buffer[]=Services.downloadFile(FilePath);
Fos.write(buffer);
Now, how can i know how much the file has been downloaded to update the progress bar
Solution
That's not easy since Services.downloadFile()
doesn't give you the file in chunks. If you had a loop, it would be simple.
If you can change the API, I suggest to change it in this way:
Services.downloadFile(File, OutputStream);
and let downloadFile()
write the file into the stream. Now you can wrap the stream and count the bytes written by overloading the various versions of write()
.
[EDIT] I saw that Services
is an RMI proxy. In this case, you can't use the approach above. Instead it gets more complex:
You need a pool of downloads on your server (think "Map"). The pool allows you to request another block of data for each download.
So on your server, you need:
- Create an object that handles the download and which has a
byte[] read()
method. - Put the objects into a map with a key. Send the key to the client somehow.
- For each object, create a thread that actually downloads the data and adds the data to a buffer. The
read()
method returns the content of the buffer and clears it.
On the client:
- You need to call a method on the server to create a new download object and start the download thread.
- Now you need a loop that calls
read()
on the download object on the server. The API is something likeread(key)
, the server looks up the key in the map and then callsread()
on the download object. - Show the progress as you write the result of the read calls to the file