使用Apache Commons FTPClient监控进度

Chr*_*een 8 java ftp ftp-client download apache-commons

我有一个简单的FTPClient类,可以从FTP服务器下载文件.我还需要监控下载的进度,但我没有看到怎样的方式.实际下载文件功能是一个简单的功能

(your ftp client name).retrieveFile(arg1,arg2);

如何监控下载进度?

谢谢,Anon.

Fem*_*emi 18

您需要一个CountingOutputStream(如Commons IO上所示:http://commons.apache.org/io/api-release/index.html).您创建其中一个,将目标OutputStream包装在其中,然后您可以按需检查ByteCount以监视下载进度.

编辑:你会做这样的事情:

int size;
String remote, local;

// do some work to initialize size, remote and local file path
// before saving remoteSource to local
OutputStream output = new FileOutputStream(local);
CountingOutputStream cos = new CountingOutputStream(output){
    protected void beforeWrite(int n){
        super.beforeWrite(n);

        System.err.println("Downloaded "+getCount() + "/" + size);
    }
};
ftp.retrieveFile(remote, cos);

output.close();
Run Code Online (Sandbox Code Playgroud)

如果您的程序是多线程的,您可能希望使用单独的线程监视进度(例如,对于GUI程序),但这是所有特定于应用程序的详细信息.