2013-03-09 186 views
3

我正在研究一个小程序,它可以将一个文件上传到我的FTP服务器并使用它来做一些其他的事情。 现在...这一切正常,我使用org.apache.commons.net.ftp FTPClient类上传。在java中的FTP apache commons进度条

ftp = new FTPClient(); 
ftp.connect(hostname); 
ftp.login(username, password); 

ftp.setFileType(FTP.BINARY_FILE_TYPE); 
ftp.changeWorkingDirectory("/shares/public"); 
int reply = ftp.getReplyCode(); 

if (FTPReply.isPositiveCompletion(reply)) { 
    addLog("Uploading..."); 
} else { 
    addLog("Failed connection to the server!"); 
} 

File f1 = new File(location); 
in = new FileInputStream(

ftp.storeFile(jTextField1.getText(), in); 

addLog("Done"); 

ftp.logout(); 
ftp.disconnect(); 

应上传的文件在hTextField1中命名。 现在...我如何添加进度条?我的意思是,ftp.storeFile中没有流...我如何处理这个问题?

感谢您的帮助! :)

问候

回答

21

你可以使用它CopyStreamListener,根据Apache的公共文档就是the listener to be used when performing store/retrieve operations.

CopyStreamAdapter streamListener = new CopyStreamAdapter() { 

    @Override 
    public void bytesTransferred(long totalBytesTransferred, int bytesTransferred, long streamSize) { 
     //this method will be called everytime some bytes are transferred 

     int percent = (int)(totalBytesTransferred*100/yourFile.length()); 
     // update your progress bar with this percentage 
    } 

}); 
ftp.setCopyStreamListener(streamListener); 

希望这有助于

+1

哦,太感谢你了,那工作! 但现在我又遇到了另一个问题...如果我按上传文件的按钮,程序会冻结,如果上传完成,完整的进度条已满... – cuzyoo 2013-03-09 11:27:17

+1

这是因为您在GUI线程中上传,因此GUI会冻结,并等待上传完成,这是避免使用[Threads](http://docs.oracle.com/javase/7/docs/api/java/lang/Thread。 html),有一个例子:[Thread Example](http://www.javabeginner.com/learn-java/java-threads-tutorial) – BackSlash 2013-03-09 11:31:09

+0

感谢您的帮助! – cuzyoo 2013-03-09 11:36:29