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

前端 未结 2 1584
甜味超标
甜味超标 2021-02-10 21:26

I have a web application which needs to perform a file copy operation and show user a progress bar.

Currently, the copy is being done by calling cpio which

2条回答
  •  醉酒成梦
    2021-02-10 21:52

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

    import java.io.*;
    
    public class FileCopyProgress {
        public static void main(String[] args) {
            System.out.println("copying file");
            File filein  = new File("test.big");
            File fileout = new File("test_out.big");
            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");
            }
        }
    }
    

    You would have to somehow update your progress bar instead of the System.out.println(). I hope this helps, but maybe i did not understand your question.

提交回复
热议问题