JAVA实现FTP文件批量下载文件到本地文件夹
/**
*FTP文件批量下载文件到本地文件夹
*
* @ftpath FTP文件路径
* @ftpname FTP上文件名
* @localfile 本地路径
*/
public static void download() {
FTPClient ftp = new FTPClient();
try {
ftp.connect(ftphost, ftpport);
ftp.login(ftpusername, ftppassword);
if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
logger.info("连接失败,用户名或密码错误");
} else {
logger.info("下载FTP连接成功");
}
// 连接FTP目录
ftp.changeWorkingDirectory(ftpath);
FTPFile[] ftps = ftp.listFiles();
for (FTPFile ftpFile : ftps) {
// 解决中文乱码
byte[] bytes = ftpFile.getName().getBytes("iso-8859-1");
String string = new String(bytes, "UTF-8");
logger.info("开始下载" + string + "文书");
if (string.endsWith("zip")) {
// 开始准备下载到本地
logger.info(ftpname + "开始时间:");
File file = new File(ftp.printWorkingDirectory() + local
+ "/" + ftpFile.getName());
// 判断文件夹是否存在,如果不存在则创建
if (!file.exists()) {
file.getParentFile().mkdir();
file.createNewFile();
}
OutputStream is = new FileOutputStream(file);
ftp.retrieveFile(ftpFile.getName(), is);
logger.info(ftpname + "结束时间:");
is.close();
}
}
logger.info("下载完成");
} catch (IOException e) {
e.printStackTrace();
logger.error("下载文件错误");
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}