12

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

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

4 回答 4

33

增加缓冲区大小:

client.setBufferSize(1024000);
于 2013-02-02T11:07:55.790 回答
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();
于 2013-01-19T21:21:53.233 回答
1

有一个已知的 Java 1.7 和 Commons Net 3.2 发布,错误是https://issues.apache.org/jira/browse/NET-493

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

于 2013-12-11T02:50:58.347 回答
0

最好使用 ftp.setbuffersize(0); 如果您使用 0 作为您的 buffersize ,它将作为无限的缓冲区大小。显然你的交易会得到加速......我亲身经历过......一切顺利...... :)

于 2013-08-12T17:53:55.957 回答