1、相关的函数
/**
* Description: 从FTP服务器下载文件
* @param url FTP服务器hostname
* @param port FTP服务器端口
* @param username FTP登录账号
* @param password FTP登录密码
* @param remotePath FTP服务器上的相对路径
* @param fileName 要下载的文件名
* @param localPath 下载后保存到本地的路径
* @return
*/
public static boolean downFtpFile(String host, int port,String username, String password, String remotePath,String fileName,String localPath) {
boolean downloadReplay = false;
FTPClient ftpClient = null;
OutputStream os = null;
try {
ftpClient = getFTPClient(host, username, password, port);
ftpClient.setControlEncoding("UTF-8"); // 中文支持
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
ftpClient.changeWorkingDirectory(remotePath);
FTPFile[] fs = ftpClient.listFiles();
for(FTPFile ff:fs){
String remoteFileName = ff.getName();
if(remoteFileName.indexOf(fileName)>-1 && remoteFileName.indexOf(".csv")>-1){
File localFile = new File(localPath + File.separatorChar + "weather.csv");
os = new FileOutputStream(localFile);
ftpClient.retrieveFile(remotePath+remoteFileName, os);
os.close();
downloadReplay = true;
}
}
ftpClient.logout();
} catch (IOException e) {
logger.error(e.getMessage(), e);
} finally {
IOUtils.closeQuietly(os);
if (ftpClient.isConnected()) {
try {
ftpClient.disconnect();
} catch (IOException ioe) {
logger.error(ioe.getMessage(), ioe);
}
}
}
return downloadReplay;
}
/**
* 登录FTP
* @param ftpHost
* @param ftpUserName
* @param ftpPassword
* @param ftpPort
* @return
*/
public static FTPClient getFTPClient(String ftpHost, String ftpUserName,
String ftpPassword, int ftpPort) {
FTPClient ftpClient = new FTPClient();
try {
ftpClient = new FTPClient();
ftpClient.connect(ftpHost, ftpPort);// 连接FTP服务器
ftpClient.login(ftpUserName, ftpPassword);// 登陆FTP服务器
if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
logger.info("未连接到FTP,用户名或密码错误。");
ftpClient.disconnect();
} else {
logger.info("FTP连接成功。");
}
} catch (SocketException e) {
logger.error(e.getMessage());
logger.error("FTP的IP地址可能错误,请正确配置。");
} catch (IOException e) {
logger.error(e.getMessage());
logger.error("FTP的端口错误,请正确配置。");
}
return ftpClient;
}
2、测试:
SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
String fileName = df.format(Util.getDayTimeByNum(new Date(), -1));//文件名为例如20180710.csv
String host = "10.24.23.xx";
int port = 21;
String username = "xxx";
String password = "xxx";
String remotePath = "/aa/";//这里有一个坑,ftp的根目录为opt,文件在/opt/aa/下但是这里不行写remotePath = "/opt/aa/",否则找不到
String localPath = "/bb/cc/";
boolean isDown = Util.downFtpFile(host, port, username, password, remotePath, fileName, localPath);