Posted on 2007-10-22 09:43
詩特林 閱讀(11576)
評論(15) 編輯 收藏 所屬分類:
Socket
用Java實現FTP批量大文件上傳下載(二)
用Java實現FTP批量大文件上傳下載(一)
2 上傳下載
文件的上傳可以分成多線程及單線程,在單線程情況下比較簡單,而在多線程的情況下,要處理的事情要多點,同時也要小心很多。下面是net.sf.jftp.net.FtpConnection的上傳handleUpload方法。已經考慮了單線程及多線程兩種不同的類型。
public int handleUpload(String file, String realName)

{
if(Settings.getEnableMultiThreading() &&
(!Settings.getNoUploadMultiThreading()))

{
Log.out("spawning new thread for this upload.");

FtpTransfer t;

if(realName != null)

{
t = new FtpTransfer(host, port, getLocalPath(), getCachedPWD(),
file, username, password, Transfer.UPLOAD,
handler, listeners, realName, crlf);
}
else

{
t = new FtpTransfer(host, port, getLocalPath(), getCachedPWD(),
file, username, password, Transfer.UPLOAD,
handler, listeners, crlf);
}

lastTransfer = t;

return NEW_TRANSFER_SPAWNED;
}
else

{
if(Settings.getNoUploadMultiThreading())

{
Log.out("upload multithreading is disabled.");
}
else

{
Log.out("multithreading is completely disabled.");
}

return (realName == null) ? upload(file) : upload(file, realName);
}
}

在多線程的情況下,有一個單獨的類net.sf.jftp.net .FtpTransfer,當然,多線程情況下,此類肯定是一個單獨的線程了。與JConnection相似,其線程的啟動也是在構造方法中啟動。而在它的run方法中,進行文件的讀取及傳輸。
public void run()

{
if(handler.getConnections().get(file) == null)

{
handler.addConnection(file, this);
}
else if(!pause)

{
Log.debug("Transfer already in progress: " + file);
work = false;
stat = 2;

return;
}

boolean hasPaused = false;

while(pause)

{
try

{
runner.sleep(100);

if(listeners != null)

{
for(int i = 0; i < listeners.size(); i++)

{
((ConnectionListener) listeners.elementAt(i)).updateProgress(file,
PAUSED,
-1);
}
}

if(!work)

{
if(listeners != null)

{
for(int i = 0; i < listeners.size(); i++)

{
((ConnectionListener) listeners.elementAt(i)).updateProgress(file,
REMOVED,
-1);
}
}
}
}
catch(Exception ex)

{
}

hasPaused = true;
}

while((handler.getConnectionSize() >= Settings.getMaxConnections()) &&
(handler.getConnectionSize() > 0) && work)

{
try

{
stat = 4;
runner.sleep(400);

if(!hasPaused && (listeners != null))

{
for(int i = 0; i < listeners.size(); i++)

{
((ConnectionListener) listeners.elementAt(i)).updateProgress(file,
QUEUED,
-1);
}
}
else

{
break;
}
}
catch(Exception ex)

{
ex.printStackTrace();
}
}

if(!work)

{
if(listeners != null)

{
for(int i = 0; i < listeners.size(); i++)

{
((ConnectionListener) listeners.elementAt(i)).updateProgress(file,
REMOVED,
-1);
}
}

handler.removeConnection(file);
stat = 3;

return;
}

started = true;

try

{
runner.sleep(Settings.ftpTransferThreadPause);
}
catch(Exception ex)

{
}

con = new FtpConnection(host, port, remotePath, crlf);

con.setConnectionHandler(handler);
con.setConnectionListeners(listeners);

int status = con.login(user, pass);

if(status == FtpConnection.LOGIN_OK)

{
File f = new File(localPath);
con.setLocalPath(f.getAbsolutePath());

if(type.equals(UPLOAD))

{
if(newName != null)

{
transferStatus = con.upload(file, newName);
}
else

{
transferStatus = con.upload(file);
}
}
else

{
transferStatus = con.download(file,this.newName);
}
}

if(!pause)

{
handler.removeConnection(file);
}
}


至于下載的過程,因為它是上傳的逆過程,與上傳的方法及寫法大同小異,在些出于篇幅的考慮,并沒有將代碼列出,但其思想及思路完全一樣。請讀者參考源代碼。
四、 進度條
可以想象,如果在上傳或是下載的過程中,沒有任何的提示,用戶根本沒法判斷任務是否完成或是任務是否死了,常常由于上傳時間或下載時間過長而誤導用戶。因此,進度條就顯得非常的重要與實用。
進度條的實現,其實說起來很簡單。就是在程序中開啟兩個線程,第一個線程用于動態的改變界面上進度條的value值,而第二個線程則在上傳或是下載的過程中,做成一個循環,在此循環中,每次讀取一定數量如8192字節數的數據。然后傳完此數據后,調用第一個線程中的updateProgress方法,來更新界面進度條的value值。
而上傳或下載的過程中(見上一節的FtpTransfer類的run方法),可以查看,con.upload(file, newName)方法,代碼如下所示,
public int upload(String file, String realName, InputStream in)

{
hasUploaded = true;
Log.out("ftp upload started: " + this);

int stat;

if((in == null) && new File(file).isDirectory())

{
shortProgress = true;
fileCount = 0;
baseFile = file;
dataType = DataConnection.PUTDIR;
isDirUpload = true;

stat = uploadDir(file);

shortProgress = false;

//System.out.println(fileCount + ":" + baseFile);
fireProgressUpdate(baseFile,
DataConnection.DFINISHED + ":" + fileCount, -1);

fireActionFinished(this);
fireDirectoryUpdate(this);
}
else

{
dataType = DataConnection.PUT;
stat = rawUpload(file, realName, in);

try

{
Thread.sleep(100);
}
catch(Exception ex)

{
}

fireActionFinished(this);
fireDirectoryUpdate(this);
}

try

{
Thread.sleep(500);
}
catch(Exception ex)

{
}

return stat;
}

此方法進行負責上傳一定字節數量的內容,其實就是調用rawUpload方法,這里沒列出,請參考源代碼,而當傳完此字節數據后,通過調用fireActionFinished()方法來調用主線程中的updateProgressBar()方法。其實代碼如下:

protected void updateProgressBar()
{
int percent = (int) (((float) lFileCompleteSize / (float) lFileSize) * 10000F);
pbFile.setValue(percent);
// System.out.println("================================================="+percent);
pbFile.setString(lFileCompleteSize / 1024L + "/" + lFileSize / 1024L
+ " kB");
percent = (int) (((float) lTotalCompleteSize / (float) lTotalSize) * 10000F);
pbTotal.setString(lTotalCompleteSize / 1024L + "/" + lTotalSize / 1024L
+ " kB");
pbTotal.setValue(percent);
repaint();
}

上面用了兩個進度條,第一個進度條表示當前文件的上傳或下載進度,第二個進度條表示所有文件下載或上傳的進度。同時,為了產生進度條的移動或變化進度幅度比較明顯,通過pbFile.setMaximum(10000)及pbTotal.setMaximum(10000)將進度條的最大值設置成10000,而不是平時我們所設置的100。筆者認為這樣比較好看,因為有的時候上傳或下載的時候由于網絡原因,可能變化比較小。若設置成100則變化不是特別明顯。