从Ftp下载某一文件夹下的所有文件(三)

private final static Log logger = LogFactory.getLog(TestOtherTrans.class);
//获取FTPClient对象
public FTPClient getFTPClient(String ftpHost, String ftpUsername, String ftpPassword, int ftpPort) {
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(ftpHost, ftpPort); //连接服务器
ftpClient.login(ftpUsername, ftpPassword);
if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
logger.info("未连接到,用户名或密码错误");
ftpClient.disconnect();
} else {
logger.info("连接成功");
}

} catch (SocketException e) {
e.printStackTrace();
logger.info("FTP的IP地址可能错误,请正确配置");
} catch (IOException e) {
e.printStackTrace();
logger.info("FTP的端口错误,请正确配置");
}
return ftpClient;
}


public void downloadFtpAllFiles(String ftpHost,int ftpPort,String ftpUsername,String ftpPassword,String ftpFilePath,String localPath) throws Exception {
FTPClient ftpClient = null;
ftpClient = getFTPClient(ftpHost, ftpUsername, ftpPassword, ftpPort);
ftpClient.setControlEncoding("UTF-8"); // 中文支持
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
ftpClient.changeWorkingDirectory(ftpFilePath);

FTPFile[] files = ftpClient.listFiles(ftpFilePath, new FTPFileFilter() {
@Override
public boolean accept(FTPFile file) {
if (file.isFile()) return true;
return false;
}
});

for (FTPFile file : files) {
File localFile = new File(localPath + File.separatorChar + file.getName());
OutputStream os = new FileOutputStream(localFile);
ftpClient.retrieveFile(file.getName(), os);
os.close();
}
ftpClient.logout();
}

@Test
public void testFTP(){
String ftpHost = "106.120.193.130";
int ftpPort = 2017;
String ftpUserName = "ftpuser";
String ftpPassword = "qwer!@#$";
String ftpPathName = "/res";
String localPath = "F:/download";
TestOtherTrans testOtherTrans = new TestOtherTrans();
try {
testOtherTrans.downloadFtpAllFiles(ftpHost, ftpPort, ftpUserName, ftpPassword, ftpPathName, localPath);
}catch(Exception e){
e.printStackTrace();
}

}
原文地址:https://www.cnblogs.com/gaoxuewei/p/6646716.html