ftp服务器目录文件及其子目录下文件下载操作:
优化:可先获取所有目录级子目录下的文件,而后遍历用线程池处理提高处理效率
①:创建连接信息
public FTPClient create() {
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect("host", 21);
boolean login = ftpClient.login("username", "password");
log.info("FTP登录结果:{}", login);
//被动模式
ftpClient.enterLocalPassiveMode();
//设置传输文件模式-文件类型
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
//传输文件的流形式
ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
//获取FTP Server响应
if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
ftpClient.disconnect();
log.error("未连接到FTP,用户名或密码错误");
}
} catch (SocketException e) {
e.printStackTrace();
log.error("FTP的端口错误,请正确配置");
} catch (IOException e) {
e.printStackTrace();
log.error("FTP的IP地址可能错误,请正确配置");
}
return ftpClient;
}
②:开始处理已存在目录文件
public void downloadFileOrDirectory(String path) {
FTPClient ftpClient = create();
//判断目录是否存在
try {
boolean isChange = ftpClient.changeWorkingDirectory(path);
if (!isChange) {
log.info("文件不存在");
return;
}
File file = new File(path);
if (!file.exists()) {
file.mkdirs();
}
//获取ftp服务器目录下的文件
FTPFile[] ftpFiles = ftpClient.listFiles(path);
downloadfile(ftpFiles, ftpClient, path);
} catch (IOException e) {
e.printStackTrace();
}
}
③:对于子目录递归遍历
private void downloadfile(FTPFile[] ftpFiles, FTPClient ftpClient, String path) {
for (FTPFile ftpFile : ftpFiles) {
if (ftpFile.isDirectory()) {
path += ftpFile.getName();
File file = new File(path += ftpFile.getName());
if (!file.exists()) {
file.mkdirs();
}
try {
FTPFile[] ftpFiles1 = ftpClient.listFiles(path);
if (ftpFiles1.length > 0) {
downloadfile(ftpFiles1, ftpClient, path);
}
} catch (IOException e) {
e.printStackTrace();
}
} else {
downFile(ftpFile, ftpClient, path);
}
}
}
④:下载ftp服务器文件(备注:md5值的计算不要放在outputStream里面的trycatch中间,不然md5值会异常)
private void downFile(FTPFile ftpFile, FTPClient ftpClient, String path) {
//本地测试时,把File.separator换成"/"
String pathFile = path + File.separator + ftpFile.getName();
File file = new File(pathFile);
if (file.exists()) {
//此处可用md5判断文件本地文件内容和ftp服务器上文件内容是否一样
//可用该ftpClient.retrieveFileStream(pathFile)的流来获取ftp服务器文件的md5值
}
try (BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(pathFile))) {
ftpClient.changeWorkingDirectory(pathFile);
//由于连接设置的编码格式为UTF-8,ftp编码格式为ISO_8859_1,需要转码,不然会文件下载失败或乱码
ftpClient.retrieveFile(new String(pathFile.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1), outputStream);
} catch (Exception e) {
throw new RuntimeException(e);
}
}