从Ftp下载某⼀⽂件夹下的所有⽂件(三)
private final static Log logger = Log(TestOtherTrans.class);
//获取FTPClient对象
public FTPClient getFTPClient(String ftpHost, String ftpUsername, String ftpPassword, int ftpPort) {
FTPClient ftpClient = new FTPClient();
try {
ftpClient.login(ftpUsername, ftpPassword);connect下载
if (!FTPReply.ReplyCode())) {
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.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 + Name());
OutputStream os = new FileOutputStream(localFile);
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();
}
}