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

前端 未结 2 1581
甜味超标
甜味超标 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:50

    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);
    }
    

提交回复
热议问题