I have the below code to copy directories and files but not sure where to measure the progress. Can someone help
as to where can I measure how much has been copied and s
Showing the progress for a file is rather simple...
long expectedBytes = src.length(); // This is the number of bytes we expected to copy..
byte[] buffer = new byte[1024];
int length;
long totalBytesCopied = 0; // This will track the total number of bytes we've copied
while ((length = in.read(buffer)) > 0){
out.write(buffer, 0, length);
totalBytesCopied += length;
int progress = (int)Math.round(((double)totalBytesCopied / (double)expectedBytes) * 100);
setProgress(progress); // From SwingWorker
}
If you want to provide information about the total number of bytes to be copied/has begin copied, it becomes a little more complicated.
You have choices here. You either pre-scan all the folders (I'd be placing the files into some kind of queue) and calculate the total bytes/number of files to be copied. Then start the actual copy process.
Updating the progress for this is as simple as the example before, except you'd be accumulating the total number of bytes you've copied over the whole process instead of a single file.
OR...
You could use a producer/consumer algorithm. The idea would be to start a thread/worker whose sole responsibility was to scan the folders for the files to be copied and place them into a central/shared queue (this is the producer).
You would have a second thread/worker that would pop the next item of this queue (blocking into a new file became available) and would actually copy the file.
The trick here is for the queue to maintain a counter to the total number of files and bytes that has passed through it, this will allow you to adjust the ongoing progress of total job...