2013-03-09 187 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