How does one display progress of a file copy operation in Java. without using Swing e.g. in a Web app?

John Doe ·

1323 Views

Here is how to copy a file in java and monitor progress on the commandline:

package com.bad.blood.test;

import java.io.*;

import org.springframework.util.ResourceUtils;

public class FileCopyProgress {
    public static void main(String[] args) throws FileNotFoundException {
        System.out.println("copying file");
        File filein  = ResourceUtils.getFile("classpath:static/images/5941188.png");
        File fileout = new File("src/main/resources/static/images/5941188_copy.png");
        FileInputStream  fin  = null;
        FileOutputStream fout = null;
        long length  = filein.length();
        long counter = 0;
        int r = 0;
        byte[] b = new byte[1024];
        try {
                fin  = new FileInputStream(filein);
                fout = new FileOutputStream(fileout);
                while( (r = fin.read(b)) != -1) {
                        counter += r;
                        System.out.println( 1.0 * counter / length );
                        fout.write(b, 0, r);
                }
        }
        catch(Exception e){
                System.out.println("foo");
        }
    }
}

Result:

copying file
0.0012724448586517551
0.0025448897173035103
0.0038173345759552656
0.0050897794346070205
0.006362224293258776
...
0.9950518794656725
0.9963243243243243
0.9975967691829761
0.9988692140416279
1.0

ref.

https://www.baeldung.com/java-copy-file

https://stackoverflow.com/questions/44399422/read-file-from-resources-folder-in-spring-boot

https://stackoverflow.com/questions/11182114/how-does-one-display-progress-of-a-file-copy-operation-in-java-without-using-sw