加速Apache Commons FTPClient传输

2022-09-05 00:39:31

我正在使用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);
        }
    }         
}

答案 1

增加缓冲区大小:

client.setBufferSize(1024000);

答案 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();

推荐