2012-07-20 77 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也修复了更多的性能问题。