jdk7 FTP连接

使用jdk7用于连接和操作ftp服务器

package com.voiinnov.xingye.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;

import sun.net.ftp.FtpClient;
import sun.net.ftp.FtpDirEntry;
import sun.net.ftp.FtpProtocolException;

public class FtpClientUtil {
	private FtpClient ftpClient;    
	
	
	public FtpClient getFtpClient(){
		return this.ftpClient;
	}
	/**
	 * 连接FTP服务器
	 * @param ip  ip地址
	 * @param port 端口号
	 * @param user 用户名
	 * @param password  密码
	 * @param path  FTP的根目录
	 */
	public void connectServer(String ip, int port, String user, String password, String path) {
		try {            
			/* ******连接服务器的两种方法*******/            
			ftpClient = FtpClient.create();            
				try {                
					SocketAddress addr = new InetSocketAddress(ip,port);
					ftpClient.connect(addr);                 
					ftpClient.login(user, password.toCharArray());
					System.out.println("login success!"); 
					//// 用2进制上传、下载
					ftpClient.setBinaryType();
					if (path!=null&&path.length() != 0){                        
						//把远程系统上的目录切换到参数path所指定的目录                        
						ftpClient.changeDirectory(path);
					}            
				} catch (FtpProtocolException e) {                
					e.printStackTrace();            
				}        
		} catch (IOException ex) {            
			ex.printStackTrace();             
		}    
	}  
	
	
	/**     
	* 关闭连接     
	*/    
	public void closeConnect() {        
		try {            
			ftpClient.close();            
				System.out.println("disconnect success");        
		} catch (IOException ex) {            
			System.out.println("not disconnect");            
			ex.printStackTrace();            
		}    
	}    
	
	/**
	 * 上传文件使用流
	 * @param localFile
	 * @param remoteFile
	 */
	public void uploadStream(String localFile, String remoteFile){
		FileInputStream is = null; 
		File file_in = new File(localFile);            
		try {
			is = new FileInputStream(file_in);
			ftpClient.putFile(remoteFile, is);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}catch (FtpProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	/**     
	* 上传文件     
	* @param localFile 本地文件     
	* @param remoteFile 远程文件     
	*/    
	public void upload(String localFile, String remoteFile) {
			//this.localfilename = localFile;        
			//this.remotefilename = remoteFile;        
			OutputStream os = null;        
			FileInputStream is = null;        
			try {            
				//将远程文件加入输出流中            
				try {                
					os = ftpClient.putFileStream(remoteFile);            
				} catch (
					FtpProtocolException e) {                
					e.printStackTrace();            
				}            
				//获取本地文件的输入流            
				File file_in = new File(localFile);            
				is = new FileInputStream(file_in);            
				//创建一个缓冲区            
				byte[] bytes = new byte[1024];            
				int c;            
				while ((c = is.read(bytes)) != -1) {
					os.write(bytes, 0, c);            
				}            
				System.out.println("upload success");        
			} catch (IOException ex) {            
				System.out.println("not upload");            
				ex.printStackTrace();            
			} finally{            
				try {                
					if(is != null){                    
						is.close();                
					}            
				} catch (IOException e) {                
					e.printStackTrace();            
				} finally {                
					try {                    
						if(os != null){                        
							os.close();                    
						}                
					} catch (IOException e) {                    
						e.printStackTrace();                
					}            
				}        
		}    
	}  
	
	/**     
	* 下载文件     
	* @param remoteFile 远程文件路径(服务器端)     
	* @param localFile 本地文件路径(客户端)     
	*/    
	public void download(String remoteFile, String localFile) {        
		InputStream is = null;        
		FileOutputStream os = null;        
		try {            
			//获取远程机器上的文件filename,借助TelnetInputStream把该文件传送到本地。            
				try {                
					is = ftpClient.getFileStream(remoteFile);            
				} catch (FtpProtocolException e) {                                
					e.printStackTrace();            
				}            
				File file_in = new File(localFile);            
				os = new FileOutputStream(file_in);            
				byte[] bytes = new byte[1024];            
				int c;            
				while ((c = is.read(bytes)) != -1) {                
					os.write(bytes, 0, c);            
				}            
				System.out.println("download success");        
		} catch (IOException ex) {            
			System.out.println("not download");            
			ex.printStackTrace();            
		} finally{            
			try {                
				if(is != null){                    
					is.close();                
				}            
			} catch (IOException e) {                
				e.printStackTrace();            
			} finally {                
				try {                    
					if(os != null){                        
						os.close();                    
					}                
				} catch (IOException e) {                    
					e.printStackTrace();                
				}            
			}        
		}    
	} 
	
	/**
	 * 
	 * @param remoteFile
	 * @return
	 */
	public String downFile2String(String remoteFile){
		InputStream is = null;  
		StringBuffer sb = null;
		BufferedReader bufferReader = null;
		try {
			is = ftpClient.getFileStream(remoteFile);
			sb = new StringBuffer();
			bufferReader = new BufferedReader(new InputStreamReader(is));
			String line = null;
			while ((line = bufferReader.readLine()) != null) {
				System.out.println("读取的数据:"+line);
				sb.append(line+"\n");
			}
		} catch (FtpProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return sb.toString();
	}
	
	/**
	 * 判断FTP服务器已经连接并且登陆
	 * @return
	 */
	private  boolean  isConAndLogin(){
		boolean flag = false;
		flag =ftpClient.isLoggedIn()&&ftpClient.isConnected();
		return flag ;
	}
	
	/**
	 * 创建目录
	 * @param path  目录名
	 * <br/>
	 * 如果需要一次性创建多个目录,可以使用这种字符串“test/test1/test2”直接创建多个目录
	 */
	public  void makeDir(String path){
		try {
			if(isConAndLogin()){
				ftpClient.makeDirectory(path);
			}else{
				System.out.println("FTP没有连接成功");
			}
			
		} catch (FtpProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 重命名
	 * @param sPath  源文件名
	 * @param dPath  目标文件名
	 */
	public  void renameDir(String sPath , String dPath ){
		try {
			if(isConAndLogin()){
				ftpClient.rename(sPath, dPath);
			}else{
				System.out.println("FTP没有连接成功");
			}
		} catch (FtpProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 递归删除文件夹
	 * @param path
	 */
	public void deleteDirs(String path) {
		try {
	            Iterator<FtpDirEntry> dirEntryI =getFtpClient().listFiles(path);
	            if(dirEntryI.hasNext()){
					FtpDirEntry entry = null;
					while(dirEntryI.hasNext()){
						entry = dirEntryI.next();
						//System.out.println(entry.getType()+"    "+entry.getName());
						if(entry.getType()==FtpDirEntry.Type.DIR){
							this.deleteDirs(path+File.separator+entry.getName());
							getFtpClient().removeDirectory(path+File.separator+entry.getName());
						}else{
							getFtpClient().deleteFile(path+File.separator+entry.getName());
						}
						
					}
				}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
	
	
	/**
	 * 删除文件夹(删除的时候文件夹必须为空)
	 * @param path
	 */
	public  void delDir(String path){
		try {
			if(isConAndLogin()){
				ftpClient.removeDirectory(path);
			}else{
				System.out.println("FTP没有连接成功");
			}
		} catch (FtpProtocolException e) {
			System.out.println("没有连接");
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * 测试删除文件夹
	 */
	public static void testDleDir(){
		FtpClientUtil fu = new FtpClientUtil();
		/* 使用默认的端口号、用户名、密码以及根目录连接FTP服务器         */  
		fu.connectServer("127.0.0.1", 21, "test", "test", null);
		String path = "20140512_back";
		fu.deleteDirs(path);
		fu.delDir(path);
		fu.closeConnect();
	}
	
	/**
	 * 测试重命名文件夹
	 */
	public static void testRenameDir(){
		FtpClientUtil fu = new FtpClientUtil();
		/* 使用默认的端口号、用户名、密码以及根目录连接FTP服务器         */  
		fu.connectServer("127.0.0.1", 21, "test", "test", null);
		String spath = "20150521";
		String dpath = "20140512_back";
		fu.renameDir(spath, dpath);
		fu.closeConnect();
	}
	
	
	/**
	 * 测试单个文件上传
	 */
	public static void testSigleUplad(){
		Date now = new Date(); 
		SimpleDateFormat sDateFormat = new SimpleDateFormat();
		sDateFormat.applyPattern("yyyyMMdd");
		String dir = "/"+sDateFormat.format(now);
		FtpClientUtil fu = new FtpClientUtil();
		/* 使用默认的端口号、用户名、密码以及根目录连接FTP服务器         */  
		fu.connectServer("127.0.0.1", 21, "test", "test", null);
		dir=dir+"/xingyeblank";
		//在FTP创建文件夹
		fu.makeDir(dir);
		//本地文件
		String localfile = "E:/test/ZXRZ_900201_TKSQ_20150521.txt";  
		//上传到ftp远程文件
		String remotefile = dir+"/ZXRZ_900201_TKSQ_20150521.txt"; 
		//上传        
		sDateFormat.applyPattern("yyyy-MM-dd   hh:mm:ss");    
		System.out.println(sDateFormat.format(new java.util.Date()));// new Date()为获取当前系统时间        
		fu.upload(localfile, remotefile);        
		System.out.println(sDateFormat.format(new java.util.Date()));// new Date()为获取当前系统时间        
		fu.closeConnect();   

	}
	
	/**
	 * 测试单个文件上传
	 */
	public static void testSigleUplad2(){
		Date now = new Date(); 
		SimpleDateFormat sDateFormat = new SimpleDateFormat();
		sDateFormat.applyPattern("yyyyMMdd");
		String dir = "/"+sDateFormat.format(now);
		FtpClientUtil fu = new FtpClientUtil();
		/* 使用默认的端口号、用户名、密码以及根目录连接FTP服务器         */  
		fu.connectServer("127.0.0.1", 21, "test", "test", null);
		dir=dir+"/xingyeblank";
		//在FTP创建文件夹
		fu.makeDir(dir);
		//本地文件
		String localfile = "E:/test/ZXRZ_900201_TKSQ_20150521.txt";  
		//上传到ftp远程文件
		String remotefile = dir+"/ZXRZ_900201_TKSQ_20150521.txt"; 
		//上传        
		sDateFormat.applyPattern("yyyy-MM-dd   hh:mm:ss");    
		System.out.println(sDateFormat.format(new java.util.Date()));// new Date()为获取当前系统时间        
		fu.uploadStream(localfile, remotefile);  
		System.out.println(sDateFormat.format(new java.util.Date()));// new Date()为获取当前系统时间        
		fu.closeConnect();   

	}
	
	/**
	 * 测试文件加载
	 */
	public static void testDownFile(){
		//下载到本地文件
		String localfile = "E:/test/AESUtils副本3333.java";  
		//ftp远程文件
		String remotefile = "20150521/xingyeblank/AESUtils111.java";
		FtpClientUtil fu = new FtpClientUtil();
		/* 使用默认的端口号、用户名、密码以及根目录连接FTP服务器         */  
		fu.connectServer("127.0.0.1", 21, "test", "test", null);
		fu.download(remotefile, localfile);
	}
	
	public static void testDownFile2String(){
		//ftp远程文件
		String remoteFile = "20150521/xingyeblank/ZXRZ_900201_TKSQ_20150521.txt";
		FtpClientUtil fu = new FtpClientUtil();
		/* 使用默认的端口号、用户名、密码以及根目录连接FTP服务器         */  
		fu.connectServer("127.0.0.1", 21, "test", "test", null);
		String str = fu.downFile2String(remoteFile);
		System.out.println(str);
	}
	
	/**
	 * 测试创建文件夹
	 */
	public static void testMakeDir(){
		FtpClientUtil fu = new FtpClientUtil();
		/* 使用默认的端口号、用户名、密码以及根目录连接FTP服务器         */  
		fu.connectServer("127.0.0.1", 21, "test", "test", null);
		try {
			fu.getFtpClient().makeDirectory("20150521/test");
			fu.getFtpClient().makeDirectory("20150521/test2");
			fu.getFtpClient().makeDirectory("20150521/test3");
			fu.getFtpClient().makeDirectory("20150521/test4");
			fu.getFtpClient().makeDirectory("20150521/test5");
			fu.closeConnect();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String agrs[]) {  
		//testSigleUplad();
		//testMakeDir();
		//testRenameDir();
		//testDleDir();
		//testDownFile();
		//testDownFile2String();
		testSigleUplad2();
		
		//---------------其他方法的说明----------------
		//从FTP下载指定的文件到OutputStream下
		//ftpClient.getFile(String remotePath, OutputStream);
		//如果是文件名列出文件信息,如果是目录则列出文件列表
		//ftpClient.list(path);
		//列出指定目录内容
		//ftpClient.nameList(path);
	}

}

猜你喜欢

转载自liuna718-163-com.iteye.com/blog/2213472