Suppose I have the following code that will download something from my website.
URL website = new URL(url);
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream("something.zip");
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
I want to make a JProgressBar that would display the progress of the file that is being downloaded. To achieve this, I know that one way is to get the total size of the file and the currently downloaded bytes of the file, then get the percent. Here is the following code for getting the size of the file:
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("HEAD");
long fileSize = conn.getContentLengthLong();
However, getting the downloaded bytes of FileOutputStream is difficult, because you have to make loop that keeps track of the current bytes that are being downloaded. How would you be able to achieve this then?
Note: The algorithm should be suitable for very large files, as the files I am downloading from the internet are one gigabyte in size.
I provide below the code snippet you can look into it. Basically, you have to calculate the number of bytes and then make a calculation by diving into 100 to make some percentage.
InputStream inputStream = util.getInputStream();
// opens an output stream to save into file
FileOutputStream outputStream = new FileOutputStream(saveFilePath);
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = -1;
long totalBytesRead = 0;
int percentCompleted = 0;
long fileSize = util.getContentLength();
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
totalBytesRead += bytesRead;
percentCompleted = (int) (totalBytesRead * 100 / fileSize);
setProgress(percentCompleted);
For more details, refer this link