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

[经验分享] common-net ftp封装

[复制链接]

尚未签到

发表于 2016-6-9 04:18:43 | 显示全部楼层 |阅读模式
public class FTPSystem {
private FTPClient client = new FTPClient();
private int port;
private String ip;
private String user;
private String pw;
private String dirId;
private LogFactory log = LogFactory.getLog();
private boolean preConn = false;
public FTPSystem(String ip,String user,String pw,int port){
this.port = port;
this.ip = ip;
this.user = user;
this.pw = pw;
if(connect()){
preConn = true;
}
}
/**
*
* 连接服务器
*
* @return
* @author      YitianC
* @history
*              YitianC Oct 28, 2011 5:13:43 PM
*/
public boolean connect() {
synchronized(this){
if(client.isConnected()){
preConn = true;
return true;
}
long startTime = System.currentTimeMillis();
try {
client.setTimeOut(2000);
client.connect(ip, port);
client.login(user, pw);
int reply = client.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
client.disconnect();
return false;
}
preConn = true;
return true;
}  catch (Exception e) {
log.printException(null, e);
}
finally{
log.debug("FTP connection cost time "+(float)(System.currentTimeMillis()-startTime)/1000+" seconds.");
}
return false;
}
}
public void test(){
FTPFile[] fs = null;
try {
//fs = this.getFiles(new String("/home/root/listenerDebug/十大二".getBytes("gbk"),"iso-8859-1"));
fs = this.getFiles("/home/root/listenerDebug/十大二");
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
for(FTPFile f:fs){
try {
System.out.println(new String(f.getName().getBytes("iso-8859-1"),"gbk"));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
System.out.println(this.isExist("/home/root/listenerDebug/flex配置文档1.docx"));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*try {
this.put("d:/listenerDebug/normal/flex配置文档1.docx", "/home/root/listenerDebug");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
//this.get("/home/root/listenerDebug/flex配置文档1.docx", "d:/listenerDebug/normal/flex配置文档1.docx");
}
/**
*
* 上传
*
* @param localPath
* @param remotePath
* @return
* @author      YitianC
* @history
*              YitianC Oct 26, 2011 12:28:28 PM
*/
public boolean put(String localPath,String remotePath)throws Exception{
synchronized(this){
if(localPath==null || remotePath==null)
return false;
File localFile = new File(localPath);
if(!localFile.exists()) return false;
if(!preConn)return false;
if(!connect()){
return false;
}
if(!mkdir(remotePath)){
System.out.println("无法建立目录 "+remotePath);
return false;
}
String fileName = localFile.getName();
try{
fileName = new String(fileName.getBytes("gbk"),"iso-8859-1");
}catch(Exception e){
}
String remoteFile = DirUtil.dirAddFileName(remotePath, fileName);
DataInputStream dis =null;;
try {
client.setFileType(FTPClient.BINARY_FILE_TYPE);// 必须是二进制类型,不然会导致错误
dis= new DataInputStream(new FileInputStream(localFile));
return client.storeFile(remoteFile, dis);
} catch (IOException e) {
log.printException(null, e);
}
finally{
if(dis!=null){
dis.close();
}
}
return false;
}
}
/**
*
* 下载
*
* @param remoteName
* @param localPath
* @return
* @author      YitianC
* @history
*              YitianC Oct 26, 2011 12:28:35 PM
*/
public boolean get(String remoteName,String localPath){
synchronized(this){
if(!preConn)return false;
if(!connect()) return false;
// 分段读取
DataOutputStream os = null;
try {
client.setFileType(FTPClient.BINARY_FILE_TYPE);// 必须是二进制类型,不然会导致错误
os = new DataOutputStream(new FileOutputStream(localPath));
return client.retrieveFile(remoteName, os);
} catch (Exception e) {
e.printStackTrace();
log.printException(null, e);
return false;
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
log.printException(null, e);
}
}
}
}
}
/**
*
* 根据文件名取得文件大小  
*
* @param name  文件名
* @return
* @author      YitianC
* @history
*              YitianC Oct 28, 2011 5:14:33 PM
*/
public long getFileSize(String name){
FTPFile file = this.getFile(name);
if(file == null) return 0;
return file.getSize();
}
/**
*
* 取得文件的详细信息
*
* @param path 文件路径
* @return
* @author      YitianC
* @history
*              YitianC Oct 28, 2011 5:15:03 PM
*/
public FTPFile getFile(String path){
synchronized(this){
if(!preConn)return null;
if(!connect()) return null;
FTPFile[] f;
try{
path = new String(path.getBytes("gbk"),"iso-8859-1");
}catch(Exception e){
}
try {
f = client.listFiles(path);
} catch (Exception e) {
log.printException(null, e);
return null;
}
if(f==null){
return null;
}
else if(f.length==0){
return null;
}
FTPFile file = f[0];
f = null;
return file;
}
}
/**
*
* 进入FTP目录 相当于cd命令
*
* @param path
* @return
* @author      YitianC
* @history
*              YitianC Oct 28, 2011 5:16:22 PM
*/
public boolean cd(String path){
synchronized(this){
try {
if(!preConn)return false;
return client.changeWorkingDirectory(path);
} catch (IOException e) {
log.printException(null, e);
}
return false;
}
}
/**
*
* 判断文件或路径是否存在
*
* @param path
* @return
* @author      YitianC
* @history
*              YitianC Oct 28, 2011 5:16:47 PM
*/
public boolean isExist(String path){
synchronized(this){
if(!preConn)return false;
FTPFile[] f;
String fileName = DirUtil.getLastPathName(path);
try{
fileName = new String(fileName.getBytes("gbk"),"iso-8859-1");
}catch(Exception e){
}
try {
f = client.listFiles(DirUtil.getParentPath(path));
if(f!=null){
for(FTPFile ff:f){
if(ff.getName().equals(fileName)){
return true;
}
}
}
} catch (Exception e) {
log.printException(null, e);
return false;
}
return false;
}
}
/**
*
* 取得path目录下的文件列表  
*
* @param path
* @return
* @author      YitianC
* @history
*              YitianC Oct 28, 2011 5:17:06 PM
*/
public FTPFile[] getFiles(String path){
synchronized(this){
if(!preConn)return null;
if(!connect()) return null;
try{
path = new String(path.getBytes("gbk"),"iso-8859-1");
}
catch(Exception e){
}
try {
return client.listFiles(path);
} catch (IOException e) {
log.printException(null, e);
}
return null;
}
}
/**
*
* 移动文件
*
* @param path  原路径
* @param newPath新路径
* @return
* @author      YitianC
* @history
*              YitianC Oct 28, 2011 5:17:22 PM
*/
public boolean move(String path,String newPath){
synchronized(this){
if(!preConn)return false;
if(!connect())return false;
try {
return client.rename(path, newPath);
} catch (IOException e) {
log.printException(null, e);
}
return false;
}
}
public void printFiles(FTPFile[] files){
synchronized(this){
if(files==null) return;
for(FTPFile f:files){
log.debug("name="+f.getName());
}
}
}
/**
*
* 建立目录
*
* @param path
* @return
* @author      YitianC
* @history
*              YitianC Oct 28, 2011 5:18:01 PM
*/
public boolean mkdir(String path){
synchronized(this){
if(!preConn)return false;
if(!connect())return false;
if(this.isExist(path))return true;
path = this.getEncodePath(path);
try {
return mkd(path);
} catch (Exception e) {
log.printException(null, e);
return false;
}
}
}
public boolean mkd(String path)throws Exception{
synchronized(this){
if(!preConn)return false;
if(!connect())return false;
if(!this.isExist(path)){
if(!mkd(DirUtil.getParentPath(path))){
return false;
}
int rt = client.mkd(path);
if(this.isExist(path)){
return true;
}
return false;
}
return true;
}
}
/**
*
* 断开连接
*
* @return
* @author      YitianC
* @history
*              YitianC Oct 28, 2011 5:18:19 PM
*/
public boolean disConnect(){
synchronized(this){
if(!preConn)return true;
if(client.isConnected()){
try {
client.disconnect();
return true;
} catch (IOException e) {
log.printException(null, e);
return false;
}
}
return true;
}
}
public String getEncodePath(String path){
try {
String npath = new String(path.getBytes("utf-8"),"iso-8859-1");
path = npath;
} catch (UnsupportedEncodingException e1) {
log.printException(null, e1);
}catch(Exception e){
log.printException(null, e);
}
return path;
}
public boolean rmDir(String path){
synchronized(this){
try{
if(!preConn)return false;
path = this.getEncodePath(path);
client.rmd(path);
}catch(Exception e){
log.printException(null, e);
return false;
}
}
return !this.isExist(path);
}
public boolean rmEmptyDir(String path){
try{
String paDir = DirUtil.getParentPath(path);
FTPFile f [] = this.getFiles(path);
if(f == null){
return true;
}
else if(f.length==0){
return true;
}
else if(f.length==2){
String name1 = f[0].getName();
String name2 = f[1].getName();
if(name2==null||name1==null){
return false;
}
else{
if((name2.equals(".")&&name1.equals(".."))||(name1.equals(".")&&name2.equals(".."))){
if(!this.rmDir(path)){
return false;
}
else {
return rmEmptyDir(paDir);
}
}
else{
return false;
}
}
}
}catch(Exception e){
log.printException(null, e);
}
return false;
}
public void release(){
if(disConnect()){
client = null;
}
}
public static void main(String[] args){
FTPSystem f = new FTPSystem("172.19.201.200","weblogic","web123",21);
f.test();
}
public String getDirId() {
return dirId;
}
public void setDirId(String dirId) {
this.dirId = dirId;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getPw() {
return pw;
}
public void setPw(String pw) {
this.pw = pw;
}
public boolean isPreConn() {
return preConn;
}
public void setPreConn(boolean preConn) {
this.preConn = preConn;
}
}
  
  好像这个版本的不支持设置连接超时,所以重写了个
  

class FTPClient extends org.apache.commons.net.ftp.FTPClient{
private SocketFactory _socketFactory_=SocketFactory.getDefault();
private int timeOut = 2000;
public FTPClient(){
}
public void connect(InetAddress host, int port)
throws SocketException, IOException
{
_socket_=this._socketFactory_.createSocket();
_socket_.connect(new InetSocketAddress(host, port), timeOut);
_connectAction_();
}
public void connect(String hostname, int port)
throws SocketException, IOException
{
connect(InetAddress.getByName(hostname), port);
}
public void setConnTimeOut(int timeOut){
}
public int getTimeOut() {
return timeOut;
}
public void setTimeOut(int timeOut) {
this.timeOut = timeOut;
}
}

  

运维网声明 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-227936-1-1.html 上篇帖子: ftp 500 OOPS: cannot change directory 下篇帖子: android ftp客户端
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

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

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

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

扫描微信二维码查看详情

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


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


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


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



合作伙伴: 青云cloud

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