FTPClient下载损坏的文件

时间:2017-08-10 11:28:56

标签: java ftp

当ftp服务器通过FTPClient类文件下载文件损坏时,检查初始文件(img1)和下载文件(img2)

来源:

public class FtpClient extends FTPClient {

private String host;
private int port;
private String username;
private String password;
private boolean connected;

public FtpClient(String host, int port, String username, String password) {
    this.host = host;
    this.port = port;
    this.username = username;
    this.password = password;

    connected = connect();
}


private void verifyConnection() throws ConnectionException {
    if(!connected){
        ConnectionException ex = new ConnectionException();
        log.error(ex.getMessage());
        throw ex;
    }
}


private boolean connect(){
    try {
        //try to connect
        connect(host, port);

        if(!login(username, password)){
            logout();
            return false;
        }

        int reply = getReplyCode();

        if(!FTPReply.isPositiveCompletion(reply)){
            disconnect();
            return false;
        }
        enterRemotePassiveMode();
        setFileTransferMode(BINARY_FILE_TYPE);
        setFileType(BINARY_FILE_TYPE);

        log.debug("Remote system is " + getSystemType());
        log.debug("Current directory is " + printWorkingDirectory());

        return true;
    } catch (IOException e) {
        log.error(e.getMessage());
        e.printStackTrace();

        return false;
    }
}

public void get(String batchName, String fileName) throws IOException, ConnectionException {
    verifyConnection();
    File file = new File("/tmp/" + batchName);

    if (!file.exists()){
        boolean mkdir = file.mkdir();
        log.info("Create batch directory '{}' result: {}",batchName,  mkdir);
    }
    OutputStream outputStream = new FileOutputStream("/tmp/" + batchName + "/" + fileName);
    boolean result = retrieveFile(batchName + "/" + fileName, outputStream);

    log.debug("Retrieve file {}, result: {}", batchName + "/" + fileName, result);
    outputStream.close();
}
}

IMG1 img1

IMG2 img2

出了什么问题?

1 个答案:

答案 0 :(得分:0)

您对FTPClient.setFileTransferMode使用的CONSTANT不正确。

setFileTransferMode(BINARY_FILE_TYPE);

就像医生说的那样:

  

模式 - 要使用的新传输模式(FTP类_TRANSFER_MODE常量之一)。

您可以使用其中之一:

  • FTP.BLOCK_TRANSFER_MODE
  • FTP.COMPRESSED_TRANSFER_MODE
  • FTP.STREAM_TRANSFER_MODE

这可能会纠正您的转移问题,因为您使用的值可能是任何值......

您传递的值为2,期望[10|11|12]之一。所以它可能保留默认的STREAM_TRANSFER_MODE值。