2012-07-20 78 views
10

我使用Apache Commons FTPClient上傳大文件,但傳輸速度只是使用WinSCP通過FTP傳輸速度的一小部分。我怎樣才能加快我的轉移?加快Apache Commons FTPClient傳輸

public boolean upload(String host, String user, String password, String directory, 
     String sourcePath, String filename) throws IOException{ 

    FTPClient client = new FTPClient(); 
    FileInputStream fis = null; 

    try { 
     client.connect(host); 
     client.login(user, password); 
     client.setControlKeepAliveTimeout(500); 

     logger.info("Uploading " + sourcePath); 
     fis = new FileInputStream(sourcePath);   

     // 
     // Store file to server 
     // 
     client.changeWorkingDirectory(directory); 
     client.setFileType(FTP.BINARY_FILE_TYPE); 
     client.storeFile(filename, fis); 
     client.logout(); 
     return true; 
    } catch (IOException e) { 
     logger.error("Error uploading " + filename, e); 
     throw e; 
    } finally { 
     try { 
      if (fis != null) { 
       fis.close(); 
      } 
      client.disconnect(); 

     } catch (IOException e) { 
      logger.error("Error!", e); 
     } 
    }   
} 

回答

26

增加緩衝區大小:

client.setBufferSize(1024000); 
+1

Apache版本3.3存在將BufferSize設置爲零的問題,因爲它會使用默認值(8192)而不是無限制的值。 – Thinhbk 2013-11-19 11:39:24

+0

我不得不從版本3.2更新到版本3.5,它的工作,否則仍然很慢。也許3.3工程雖然。 – JohnyTex 2016-06-14 17:24:23

2

使用outputStream方法,並使用緩衝區進行傳輸。

InputStream inputStream = new FileInputStream(myFile); 
OutputStream outputStream = ftpclient.storeFileStream(remoteFile); 

byte[] bytesIn = new byte[4096]; 
int read = 0; 

while((read = inputStream.read(bytesIn)) != -1) { 
    outputStream.write(bytesIn, 0, read); 
} 

inputStream.close(); 
outputStream.close(); 
+1

這個答案幫了我很多。它顯着加速。 – 2016-02-04 16:07:05

0

如果使用 ftp.setbuffersize(0)這將是更好; 如果你使用0作爲緩衝區大小,它會佔用無限大的緩衝區大小。 明顯烏爾交易將得到加快......我親身經歷吧.. 一路走好... :)

1

有一個已知的與Java 1.7和共享網絡3.2發行,這個錯誤是https://issues.apache.org/jira/browse/NET-493

如果運行這些版本,我建議升級到Commons Net 3.3作爲第一步。顯然3.4也修復了更多的性能問題。