【问题标题】:Speed up Apache Commons FTPClient transfer加速 Apache Commons FTPClient 传输
【发布时间】:2012-07-19 07:56:47
【问题描述】:

我正在使用 Apache Commons FTPClient 上传大文件,但传输速度只是使用 WinSCP 通过 FTP 传输速度的一小部分。如何加快传输速度?

    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);
        }
    }         
}

【问题讨论】:

    标签: java ftp apache-commons


    【解决方案1】:

    使用 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();
    

    【讨论】:

    • 这个答案对我帮助很大。它显着加速。
    【解决方案2】:

    增加缓冲区大小:

    client.setBufferSize(1024000);
    

    【讨论】:

    • Apache 3.3 版存在将 BufferSize 设置为零的问题,因为它将使用默认值 (8192) 而不是预期的无限值。
    • 我不得不从 3.2 版更新到 3.5 版并且它工作正常,否则仍然很慢。也许 3.3 可以工作。
    【解决方案3】:

    如果你使用它会更好 ftp.setbuffersize(0); 如果您使用 0 作为您的 buffersize ,它将作为无限的缓冲区大小。 显然你的交易会加快...我亲身经历过.. 万事如意... :)

    【讨论】:

      【解决方案4】:

      Java 1.7 和 Commons Net 3.2 有一个已知问题,bug 是https://issues.apache.org/jira/browse/NET-493

      如果运行这些版本,我建议首先升级到 Commons Net 3.3。显然 3.4 也修复了更多的性能问题。

      【讨论】:

        猜你喜欢
        • 2012-03-31
        • 2023-04-05
        • 2013-11-21
        • 2015-01-17
        • 2011-03-09
        • 2014-03-26
        • 2011-08-18
        • 2012-05-22
        • 2016-03-16
        相关资源
        最近更新 更多