用到的jar包: comments-net.jar
下载地址:http://download.youkuaiyun.com/detail/xuanjiewu/9838448
这里仅仅是对ftp工具类的简单使用,很多东西还不是很了解。当然学以致用,先用到这里吧。
很多知识点是相互联系的,希望以后的例子中能够结合更多的知识点进行实例编写,这样也有助于知识的巩固。
参见:
http://blog.youkuaiyun.com/techbirds_bao/article/details/8593706
http://blog.youkuaiyun.com/kardelpeng/article/details/6588284
封装
/**
* FTP 连接服务
* @param ftpHost
* @param ftpPort
* @param ftpUserName
* @param ftpPassword
* @return
*/
public static FTPClient getFTPClient(String ftpHost, int ftpPort, String ftpUserName, String ftpPassword) {
FTPClient ftpClient = null;
try {
ftpClient = new FTPClient();
ftpClient.connect(ftpHost, ftpPort);// 连接FTP服务器
ftpClient.login(ftpUserName, ftpPassword);// 登陆FTP服务器
if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
System.out.println("未连接到FTP,用户名或密码错误!");
ftpClient.disconnect();
} else {
System.out.println("FTP连接成功!");
}
} catch (SocketException e) {
e.printStackTrace();
System.out.println("FTP的IP地址可能错误,请正确配置!");
} catch (IOException e) {
e.printStackTrace();
System.out.println("FTP的端口错误,请正确配置!");
}
return ftpClient;
}
/**
* FTP文件下载/读取
* @param ftpServer
* @param ftpPort
* @param ftpUser
* @param ftpPwd
* @param fileName
* @param filePath
* @param localPath
*/
public static String ftpDownload(String ftpServer, int ftpPort, String ftpUser,String ftpPwd,String filePath,String fileName,String localPath){
String message = "";
try {
FTPClient ftp = getFTPClient(ftpServer, ftpPort, ftpUser, ftpPwd);
ftp.changeWorkingDirectory(filePath); //转移到FTP服务器目录
File localFile = new File(localPath + fileName);
OutputStream os = new FileOutputStream(localFile);
ftp.retrieveFile(fileName, os);
os.close();
System.out.println("FTP文件:"+fileName+" 已成功下载到 "+localPath);
message = fileName+" 已成功下载到 "+localPath;
ftp.logout();
} catch (IOException e) {
message = "FTP文件:"+fileName+"下载失败!";
e.printStackTrace();
}
return message;
}