javaapache-commonsvfsapache-commons-vfs

How do I monitor the progress of a file transfer in Apache Commons VFS?


Using Apache Commons VFS, how do I monitor the progress of a file transfer. I need to be able to do it with uploads and downloads. I also need to monitor progress over HTTP, FTP, SFTP and FTPS. I can't find anything in the documentation about it.


Solution

  • It can be done by getting input and output streams from VFS. The following example uses a utility class from commons-net (a dependency of VFS) to manage the copying and progress-monitoring. You could equally do it manually.

    import org.apache.commons.net.io.Util;
    import org.apache.commons.net.io.CopyStreamListener;
    
    private void copy(FileObject sourceFile, FileObject destinationFile, CopyStreamListener progressMonitor) throws IOException {
        InputStream sourceFileIn = sourceFile.getContent().getInputStream();
        try {
            OutputStream destinationFileOut = destinationFile.getContent().getOutputStream();
            try {
                Util.copyStream(sourceFileIn, destinationFileOut, Util.DEFAULT_COPY_BUFFER_SIZE, sourceFile.getContent().getSize(), progressMonitor);
            } finally {
                destinationFileOut.close();
            }
        } finally {
            sourceFileIn.close();
        }
    }