public class FtpService {
public FTPClient ftp = null;
/**
* 初始化ftp服务器
* @param ip
* @param port
* @param username
* @param password
*/
public boolean initFtp(String ip,Integer port,String username,String password) {
ftp = new FTPClient();
ftp.setControlEncoding("utf-8");
System.out.println("连接ftp服务器: 网址"+ip+" :端口"+port);
try {
ftp.connect(ip, port);
ftp.login(username, password);
int replyCode = ftp.getReplyCode();
if(!FTPReply.isPositiveCompletion(replyCode)) {
System.out.println("连接ftp服务器失败: 用户名"+username+" : 密码"+password);
return false;
}
System.out.println("连接ftp服务器成功");
} catch (SocketException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* ftp下载文件
* @param pathname ftp存放路径
* @param filename 文件名 *
* @param path 本地存放路径
* @return
*/
public void downloadImg(String pathname,String filename,String path) {
OutputStream os = null;
System.out.println("开始下载文件"+filename);
try {
ftp.changeWorkingDirectory(pathname);
FTPFile[] ftpFiles = ftp.listFiles();
for (FTPFile file : ftpFiles) {
if(filename.equalsIgnoreCase(file.getName())) {
os = new FileOutputStream(path);
ftp.retrieveFile(file.getName(), os);
os.flush();
}
}
ftp.logout();
} catch (IOException e) {
e.printStackTrace();
}
}
}
▄█▀█●老铁,站住!别跑,我又不收你钱,如果我的demo能够帮助到你,请给我一个赞吧!