public static void main(String[] args) {
/*
* FTPUtil myFtp = new FTPUtil(); try { myFtp.connect("127.0.0.1", 21,
* "ftp", "123456"); myFtp.download("t.txt", "G:/test.txt");
* myFtp.disconnect(); } catch (IOException e) {
* System.out.println("连接FTP出错:" + e.getMessage()); }
*/
String result = FTPUtil.downFile("192.168.8.175", "admin", "admin", "batchsend", "D:/myFile/");
System.out.println(result);
}
public static String downFile(String ipAddress, String username,
String password, String remotePath, String targetPath) {
FTPClient ftp = new FTPClient();
try {
int reply;
ftp.connect(ipAddress);
ftp.login(username, password);// 登录
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return "connect error. code:" + reply;
}
if (StringUtils.isNotBlank(remotePath)) {
boolean flag = ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录
if(flag == false) {
return "remotePath error";
}
}
FTPFile[] fs = ftp.listFiles();
if (fs == null || fs.length == 0) {
return "not find files";
}
/*
* if(fs.length != 5) { return "files count error"; } //包括文件夹
*/
for (FTPFile ff : fs) {
if (ff.isFile()) {
File localFile = new File(targetPath + "/");
if (!localFile.exists()) {
localFile.mkdirs();
}
OutputStream is = new FileOutputStream(localFile + "/"
+ ff.getName());
ftp.retrieveFile(ff.getName(), is);
is.close();
}
}
ftp.logout();
} catch (IOException e) {
e.printStackTrace();
return "file transfer error";
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
}
}
}
return "success";
}