设为首页 收藏本站
查看: 919|回复: 0

[经验分享] 使用Apache的commons-net包实现FTP操作的类

[复制链接]

尚未签到

发表于 2016-6-10 12:09:14 | 显示全部楼层 |阅读模式
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.StringTokenizer;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import com.ea.rs4.Logger;
import com.ea.rs4.utils.StringUtils;
/**
* This class is used to upload files to ftp server or get files from ftp server
*
* @author Leo.Zhou
*/
public class FtpTool {
private static final Logger LOG = new Logger(FtpTool.class.getSimpleName());
private String ip;
private int port;
private String user;
private String pwd;
private String remotePath;
FTPClient ftpClient;
/**
* Connect to server
*
* @param ip
* @param port
* @param user
* @param pwd
* @return
* @throws FtpException
*/
public boolean connectServer(String ip, int port, String user, String pwd) throws FtpException {
boolean isSuccess = false;
try {
ftpClient = new FTPClient();
ftpClient.connect(ip, port);
ftpClient.login(user, pwd);
isSuccess = true;
} catch (Exception ex) {
LOG.error("Can not connect to remote ftp server");
throw new FtpException(ex);
}
return isSuccess;
}
/**
* Create directory
*
* @param dir
* @return
* @throws FtpException
*/
private void createDir(String dir) throws FtpException {
try {
ftpClient.setFileType(FTP.ASCII_FILE_TYPE);
StringTokenizer s = new StringTokenizer(dir, "/");
s.countTokens();
String pathName = "";
while (s.hasMoreElements()) {
String currentFolder = (String) s.nextElement();
if (currentFolder == null || currentFolder.length() == 0) {
continue;
}
pathName = pathName + (pathName.equals("")?"":"/") + currentFolder;
if(!isDirExist(pathName)) {
boolean result = ftpClient.makeDirectory(pathName);
if(!result) {
throw new FtpException(String.format("Permission denied, can not create folder : %s", pathName));
}
}
}
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
} catch (IOException e1) {
throw new FtpException(e1);
}
}
/**
* Check is directory exist
*
* @param dir
* @return
* @throws FtpException
*/
private boolean isDirExist(String dir) {
if(StringUtils.isEmpty(dir)) {
return true;
}
String preFolder = null;
String lastFolder = null;
if(dir.contains("/")) {
preFolder = dir.substring(0, dir.lastIndexOf("/"));
lastFolder = dir.substring(dir.lastIndexOf("/") + 1, dir.length());
} else {
preFolder = "";
lastFolder = dir;
}
boolean flag = false;
try {
FTPFile[] ftpFileArr = null;
if(preFolder.equals("")) {
ftpFileArr = ftpClient.listFiles();
} else {
ftpFileArr = ftpClient.listFiles(preFolder);
}
LOG.debug("Files in top folder : %s", Arrays.toString(ftpFileArr));
for (FTPFile ftpFile : ftpFileArr) {
if (ftpFile.isDirectory() && ftpFile.getName().equalsIgnoreCase(lastFolder)) {
flag = true;
break;
}
}
} catch (IOException e) {
flag = false;
}
return flag;
}
/**
* Upload file to ftp server
*
* @param remotePath
* @param localPath
* @param filename
* @throws FtpException
*/
public void uploadFile(String remotePath, File localFile) throws FtpException {
try {
if (connectServer(getIp(), getPort(), getUser(), getPwd())) {
if (!isDirExist(remotePath)) {
createDir(remotePath);
}
if (remotePath.length() != 0)
ftpClient.changeWorkingDirectory(remotePath);
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
InputStream iStream = null;
try {
iStream = new FileInputStream(localFile);
boolean result = ftpClient.storeFile(localFile.getName(), iStream);
if(!result) {
LOG.error("Upload file to FTP server failed.");
throw new FtpException("Upload file failed.");
}
} finally {
if (iStream != null) {
iStream.close();
}
}
closeServer();
}
} catch (IOException ex) {
throw new FtpException("Ftp upload file error:", ex);
}
}
/**
* Delete FTP file by link
*
* @param link
* @throws FtpException
*/
public void deleteFileByLink(String link) throws FtpException{
try {
if (connectServer(getIp(), getPort(), getUser(), getPwd())) {
ftpClient.deleteFile(getRemotePath() + "/" + link);
int status = ftpClient.getReplyCode();
LOG.debug("Ftp delete info:"+ftpClient.getReplyString());
if(status == 250) {
LOG.debug("Delete file from FTP server success.");
} else {
LOG.info("Delete file from FTP server failed.FTP status : %s, link : %s", status, link);
throw new FtpException(String.format("Delete file from FTP server failed, link : %s, FTP status : %s", link, status));
}
closeServer();
}
} catch (IOException ex) {
throw new FtpException(String.format("Delete file from FTP server failed, link : %s", link));
}
}
/**
* Close ftp server connection
*
* @throws FtpException
*/
private void closeServer() throws FtpException {
if (ftpClient.isConnected()) {
try {
ftpClient.disconnect();
} catch (IOException e) {
throw new FtpException(e);
}
}
}
/**
* @return
*/
public String getIp() {
return ip;
}
/**
* @return
*/
public int getPort() {
return port;
}
/**
* @return
*/
public String getPwd() {
return pwd;
}
/**
* @return
*/
public String getUser() {
return user;
}
/**
* @param string
*/
public void setIp(String string) {
ip = string;
}
/**
* @param i
*/
public void setPort(int i) {
port = i;
}
/**
* @param string
*/
public void setPwd(String string) {
pwd = string;
}
/**
* @param string
*/
public void setUser(String string) {
user = string;
}
/**
* @return
*/
public String getRemotePath() {
return remotePath;
}
/**
* @param string
*/
public void setRemotePath(String remotePath) {
this.remotePath = remotePath;
this.remotePath = this.remotePath.replace("\\", "/");
LOG.debug("Saving path in current system: %s", this.remotePath);
}
}

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-228637-1-1.html 上篇帖子: Configuring FTP on Exadata <转… 下篇帖子: Android中FTP服务器、客户端搭建以及SwiFTP、ftp4j介绍
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表