Peter Peter - 10 months ago 49
Java Question

How to monitor progress (JProgressBar) with FileChannels transferFrom() method?

I need a little help with the

component. My program copies files from one place to another using
java.nio FileChannels
. The actual copy method is

I've got two questions now.

  1. How to I monitor the transfer progress of FileChannels? All tutorials I've found use the conventional InputStreams and increase the progress int while looping through the inputstream.

  2. My copy methods (the FileChannel methods) are encapsulated in a separate method that is invoked by other methods that iterate though source and destination folders and then invoke the FileChannel methods for each file.

How do I implement a ProgressBar for the complete copy mechanism?

Well I should have read the FAQ a little earlier, so I guess I have to edit my initial post instead of commenting the answers, right?

Ok this is what I've done so far.
Just as jambjo suggested (thanks by the way), the
method is now looped.
BTW: Is there a preferable chunk size, or does it depend on the granularity of my progress bar just as EJP said?

Here is my code snippet:

while (position < size) {
position += destination.transferFrom(source, position, chunkSize);
current = (position/size)*100;

Unfortunately the 'current' value stays 0 within the loop and I've got no idea why.
Am I missing something?

Thanks again jambjo! I really appreciate your input!
Now that the progress monitoring of a single file works, let's address my second problem.

I'd like, no I have to, monitor progress of not only a single file, but rather a bunch of files.
My main copy methods iterates through various directories and copies appropriate files by invoking the actual transfer method.
So the copy methods don't transfer files, they are just selecting files for the actual transfer method.

Answer Source

There is no way to monitor the progress of a single invokation of transferFrom, but since you can pass it offset and length parameters, you can implement your own loop around it and update the progress bar between suitable sized chunks of data.