FTPClient踩过的坑

一、ftpClient.enterLocalPassiveMode()

    public static final int PASSIVE_LOCAL_DATA_CONNECTION_MODE = 2;

官网关于该常量的说明:

A constant indicating the FTP session is expecting all transfers to occur between the client (local) and server and that the server is in passive mode, requiring the client to connect to the server's data port to initiate a transfer

官网关于该方法的说明:

Set the current data connection mode to PASSIVE_LOCAL_DATA_CONNECTION_MODE . Use this method only for data transfers between the client and server. This method causes a PASV (or EPSV) command to be issued to the server before the opening of every data connection, telling the server to open a data port to which the client will connect to conduct data transfers. The FTPClient will stay in PASSIVE_LOCAL_DATA_CONNECTION_MODE until the mode is changed by calling some other method such as enterLocalActiveMode()

翻译如下:

将当前数据连接模式设置为被动本地数据连接模式。此方法仅用于客户端和服务器之间的数据传输。此方法导致在打开每个数据连接之前向服务器发出一个PASV(或EPSV)命令,告诉服务器打开一个数据端口,客户端将连接到该端口进行数据传输FTPClient将保持被动本地数据连接模式,直到通过调用enterLocalActiveMode()等其他方法更改模式为止。

二、ftpClient.listFiles()返回null

1、检查当前工作目录是否正确:

ftpClient.printWorkingDirectory(); 

若工作目录不正确,需切换目录:

ftpClient.changeWorkingDirectory(inpath);

2、检查文件传输模式是否是被动模式:

在ftpClient.listFiles();之前添加:

ftpClient.enterLocalPassiveMode();

三、ftpClient.retrieveFileStream(String filename)返回null

for (FTPFile ftpFile : ftpFiles) {

   inputStream = ftpClient.retrieveFileStream(ftpFile.getName());

   // ...省略其他代码

}; 

该代码只能成功下载第一个文件,从第二个文件开始inputStream都是null,原因如下:

在每次执行完下载操作之后,completePendingCommand()会一直在等FTP Server返回226 Transfer complete,但是FTP Server只有在接受到InputStream 执行close方法时,才会返回。所以一定先要执行close方法。不然在第一次下载一个文件成功之后,之后再次获取inputStream 就会返回null。

所以需要修改代码如下:

for (FTPFile ftpFile : ftpFiles) {

   inputStream = ftpClient.retrieveFileStream(ftpFile.getName());

   // ...省略其他代码

    inputStream.close();
    ftpClient.completePendingCommand();

}; 

四,带证书的FTPSClient使用

FTPSClient ftpsClient = new FTPSClient("SSL");
ftpsClient.connect(host, port);
ftpsClient.login(username, password)
//ftpsClient.setControlEncoding("UTF-8"); // 设置ftp字符集
//ftpsClient.setConnectTimeout(connectTimeout); // 设置连接超时时间,单位:毫秒
ftpsClient.enterLocalPassiveMode();// 设置被动模式,文件传输端口设置
//ftpsClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpsClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);  
ftpsClient.execPROT("P"); 
int reply = ftpsClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
            log.error("FTP server refused connection.");
            ftpsClient.logout();
            ftpsClient.disconnect();
}

 

  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值