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

空扰寡人 提交于 2019-12-03 08:24:36
snies

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.

Matt

Basically, you should use a listener pattern. In this example the listener has a single method to accept the # of bytes which were just written. It could be pre-populated with the total file size to calculate a percentage to show on the screen.

ReadableByteChannel source = ...;
WritableByteChannel dest = ...;
FileCopyListener listener = ...;


ByteBuffer buf = ByteBuffer.allocateDirect(BUFFER_SIZE);
while (src.read(buf) != -1) {
  buf.flip();
  int writeCount = dest.write(buf);
  listener.bytesWritten(writeCount);
  buf.compact();
}
buf.flip();
while (buffer.hasRemaining()) {
  int writeCount = dest.write(buf);
  listener.bytesWritten(writeCount);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!