`

common-net ftp封装

 
阅读更多
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;
	}
}

 

分享到:
评论

相关推荐

    common-net-ftp

    ftp upfile FTPClient java

    Apache Common-net Ftp客户端实例

    NULL 博文链接:https://yangyangmyself.iteye.com/blog/1299997

    common-image-3.1.1-API文档-中文版.zip

    赠送jar包:common-image-3.1.1.jar; 赠送原API文档:common-image-3.1.1-javadoc.jar; 赠送源代码:common-image-3.1.1-sources.jar; 赠送Maven依赖信息文件:common-image-3.1.1.pom; 包含翻译后的API文档:...

    flink-table-common-1.12.7-API文档-中文版.zip

    赠送jar包:flink-table-common-1.12.7.jar; 赠送原API文档:flink-table-common-1.12.7-javadoc.jar; 赠送源代码:flink-table-common-1.12.7-sources.jar; 赠送Maven依赖信息文件:flink-table-common-1.12.7....

    common-io,common-net打包奉送

    common-io,common-net打包奉送,JAVA方式实现FTP的文件上传和下载

    activiti-common-rest-5.21.0-API文档-中英对照版.zip

    赠送jar包:activiti-common-rest-5.21.0.jar; 赠送原API文档:activiti-common-rest-5.21.0-javadoc.jar; 赠送源代码:activiti-common-rest-5.21.0-sources.jar; 赠送Maven依赖信息文件:activiti-common-rest-...

    proto-google-common-protos-1.17.0-API文档-中文版.zip

    赠送jar包:proto-google-common-protos-1.17.0.jar; 赠送原API文档:proto-google-common-protos-1.17.0-javadoc.jar; 赠送源代码:proto-google-common-protos-1.17.0-sources.jar; 赠送Maven依赖信息文件:...

    proto-google-common-protos-1.17.0-API文档-中英对照版.zip

    赠送jar包:proto-google-common-protos-1.17.0.jar; 赠送原API文档:proto-google-common-protos-1.17.0-javadoc.jar; 赠送源代码:proto-google-common-protos-1.17.0-sources.jar; 赠送Maven依赖信息文件:...

    commons-net-3.7-ftp.jar

    主要用于实现ftp文件传输,网上没有很清晰的资料,故而我把自己的资料与ftpclient挂钩,希望让你尽快实现自己的项目

    weixin-java-common-3.5.0-API文档-中英对照版.zip

    赠送jar包:weixin-java-common-3.5.0.jar; 赠送原API文档:weixin-java-common-3.5.0-javadoc.jar; 赠送源代码:weixin-java-common-3.5.0-sources.jar; 赠送Maven依赖信息文件:weixin-java-common-3.5.0.pom;...

    netty-common-4.1.65.Final-API文档-中英对照版.zip

    赠送jar包:netty-common-4.1.65.Final.jar; 赠送原API文档:netty-common-4.1.65.Final-javadoc.jar; 赠送源代码:netty-common-4.1.65.Final-sources.jar; 赠送Maven依赖信息文件:netty-common-4.1.65.Final....

    glibc-common-2.17-317.el7.x86_64.rpm

    glibc-common-2.17-317

    springfox-swagger-common-3.0.0-API文档-中文版.zip

    赠送jar包:springfox-swagger-common-3.0.0.jar; 赠送原API文档:springfox-swagger-common-3.0.0-javadoc.jar; 赠送源代码:springfox-swagger-common-3.0.0-sources.jar; 赠送Maven依赖信息文件:springfox-...

    common-lang-3.1.1-API文档-中文版.zip

    赠送jar包:common-lang-3.1.1.jar; 赠送原API文档:common-lang-3.1.1-javadoc.jar; 赠送源代码:common-lang-3.1.1-sources.jar; 赠送Maven依赖信息文件:common-lang-3.1.1.pom; 包含翻译后的API文档:common...

    netty-transport-native-unix-common-4.1.73.Final-API文档-中文版.zip

    赠送jar包:netty-transport-native-unix-common-4.1.73.Final.jar; 赠送原API文档:netty-transport-native-unix-common-4.1.73.Final-javadoc.jar; 赠送源代码:netty-transport-native-unix-common-4.1.73....

    hadoop-common-2.2.0-bin-master.zip

    hadoop-common-2.2.0-bin-master(包含windows端开发Hadoop和Spark需要的winutils.exe),Windows下IDEA开发Hadoop和Spark程序会报错,原因是因为如果本机操作系统是windows,在程序中使用了hadoop相关的东西,比如写入...

    hadoop-common-2.7.3-API文档-中文版.zip

    赠送jar包:hadoop-common-2.7.3.jar; 赠送原API文档:hadoop-common-2.7.3-javadoc.jar; 赠送源代码:hadoop-common-2.7.3-sources.jar; 赠送Maven依赖信息文件:hadoop-common-2.7.3.pom; 包含翻译后的API文档...

    flink-table-common-1.13.2-API文档-中文版.zip

    赠送jar包:flink-table-common-1.13.2.jar; 赠送原API文档:flink-table-common-1.13.2-javadoc.jar; 赠送源代码:flink-table-common-1.13.2-sources.jar; 赠送Maven依赖信息文件:flink-table-common-1.13.2....

    common-io-3.1.1-API文档-中文版.zip

    赠送jar包:common-io-3.1.1.jar; 赠送原API文档:common-io-3.1.1-javadoc.jar; 赠送源代码:common-io-3.1.1-sources.jar; 赠送Maven依赖信息文件:common-io-3.1.1.pom; 包含翻译后的API文档:common-io-...

    hadoop-common-2.2.0-bin-master

    hadoop-common-2.2.0-bin-master 用于widows本地hadoop hava api开发

Global site tag (gtag.js) - Google Analytics