Copy file code with progress bar in Java

Default featured post

How does copy file progress bar works? This might be the question of many programmers including myself. The mechanism is very simple, first the size of the destination file should be retrieved and then divided to 100. In the next step while the program reads the destination  file, we can guess the progress of the file copied and show the progress result in display. For better demonstration check the following Java source code,

import java.util.*;
import java.util.Vector;

public class Test {
    public static void main(String[] args) {
        try {
            File src = new File(args[0]);
            File dst = new File(args[1]);
            test.copyFile(src, dst);
            System.out.println("File Copied!");
        } catch (Exception ex) {

    public static void copyFile(File src, File dst) throws IOException {
        try {
            InputStream in = new FileInputStream(src);
            OutputStream out = new FileOutputStream(dst);
            // Transfer bytes from in to out
            long expectedBytes = src.length(); // This is the number of bytes we expected to copy..
            long totalBytesCopied = 0; // This will track the total number of bytes we've copied
            byte[] buf = new byte[1024];
            int len = 0;
            while ((len = > 0) {
                out.write(buf, 0, len);
                totalBytesCopied += len;
                int progress = (int) Math.round(((double) totalBytesCopied / (double) expectedBytes) * 100);
                System.out.print(progress + "%  ");
                for (int i = 0; i
        } catch (Exception ex) {