您的位置:首页 > 编程语言 > PHP开发

FTP服务器文件存在性判断

2017-05-11 15:43 113 查看
在实际使用FTP文件服务器的过程中,经常需要远程下载解析文件。为提高效率,需要判断文件存在与否,有选择的进行解析。

这里对项目中的一个小片段进行备份,方便以后总结学习。

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

 /**
* 方法描述:检验指定路径的文件是否存在ftp服务器中
* @author guoxk
* @createTime 2017年5月11日 上午11:26:44
*
* @param filePath 指定绝对路径的文件 127.0.0.1:21/TEST/20161010/test_20161010.zip
* @param user     ftp服务器登陆用户名 username
* @param passward ftp服务器登陆密码 password
* @param ip       ftp的IP地址 127.0.0.1
* @param port     ftp的端口号 21
* @return 存在返回true,不存在返回false
*/
public static boolean isFTPFileExist(String filePath, String user,
String passward, String ip, int port) {
FTPClient ftp = new FTPClient();
try {
// 连接ftp服务器
ftp.connect(ip, port);
// 登陆
ftp.login(user, passward);
// 检验登陆操作的返回码是否正确
if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
ftp.disconnect();
return false;
}

ftp.enterLocalPassiveMode(); //开启本地被动模式--Linux,windowns开启主动enterLocalActiveMode

// 设置文件类型为二进制,与ASCII有区别
ftp.setFileType(FTP.BINARY_FILE_TYPE);
// 设置编码格式
ftp.setControlEncoding("GBK");

// 提取绝对地址的目录以及文件名
filePath = filePath.replace(ip + ":" + port + "/", "");
String dir = filePath.substring(0, filePath.lastIndexOf("/"));
String file = filePath.substring(filePath.lastIndexOf("/") + 1);

// 进入文件所在目录,注意编码格式,以能够正确识别中文目录
ftp.changeWorkingDirectory(new String(dir.getBytes("GBK"),
FTP.DEFAULT_CONTROL_ENCODING));

// 检验文件是否存在
InputStream is = ftp.retrieveFileStream(new String(file
.getBytes("GBK"), FTP.DEFAULT_CONTROL_ENCODING));
if (is == null || ftp.getReplyCode() == FTPReply.FILE_UNAVAILABLE) {
return false;
}

if (is != null) {
is.close();
ftp.completePendingCommand();
}
return true;
} catch (Exception e) {
//logger.error(e.getMessage());
} finally {
if (ftp != null) {
try {
ftp.disconnect();
} catch (IOException e) {
//logger.error(e.getMessage());
}
}
}
return false;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息