FTPClientUtils.java 9.69 KB
package com.bsth.util;

import java.io.ByteArrayInputStream;
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.OutputStream;
import java.io.UnsupportedEncodingException;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
/**
 * @Description: 向FTP服务器上传文件
 * 
 * @Version 1.0 2016-06-21 4:31:09 by 李强 
 * 
 */
public class FTPClientUtils {
	
	/** 
	 * @param  url FTP服务器hostname; 
	 * 
	 * - - - - port FTP服务器端口;
	 * 
	 * - - - - username FTP登录账号;
	 * 
	 * - - - - password FTP登录密码 ;
	 * 
	 * - - - - path FTP服务器保存目录;
	 * 
	 * - - - - filename 上传到FTP服务器上的文件名
	 * 
	 * - - - - input 输入流;
	 * 
	 * @return 成功返回true,否则返回false
	 * 
	 */
	public boolean uploadFile(String url,int port,String username, String password, String path, String filename, InputStream input) {
		
		boolean success = false;
		
		FTPClient ftp = new FTPClient();
		
		try {
			
			int reply;
			
			//连接FTP服务器,如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
			ftp.connect(url, port);
			
			//登录
			ftp.login(username, password);
			
			reply = ftp.getReplyCode();
			
			if (!FTPReply.isPositiveCompletion(reply)) {
				
				ftp.disconnect();
				
				return success;
				
			}
			
			ftp.changeWorkingDirectory(path);
			ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
			ftp.enterLocalPassiveMode();
			success = ftp.storeFile(new String(filename.getBytes("gbk"),"gbk"), input);
			/*success = ftp.storeFile(filename, input);	*/
			input.close();
			
			ftp.logout();
			
			// success = true;
			
		} catch (IOException e) {
			
			e.printStackTrace();
			
		} finally {
			
			if (ftp.isConnected()) {
				
				try {
					
					ftp.disconnect();
					
				} catch (IOException ioe) {
					
				}
				
			}
			
		}
		
		return success;
	}
	
	/**
	 * @Description : TOOD(将本地文件上传到FTP服务器上)
	 * 
	 * @param file
	 * 
	 * @param name
	 * 
	 * @param url
	 * 
	 * @param port
	 * 
	 * @param username
	 * 
	 * @param password
	 * 
	 * @param remotePath
	 * 
	 */
	public void FTPUpLoadFromDisk(File file,String name,String url, int port, String username, String password, String remotePath){
		
		 try { 
		        FileInputStream in=new FileInputStream(file); 
		        
		        boolean flag = uploadFile(url, port,username, password, remotePath, name, in);
		        
		      /* boolean flag = uploadFile("192.168.168.101", 21, "testftpservice", "123", "ftptest/", name, in);*/
		        
		       /* boolean flag = uploadFile("222.66.0.205", 21, "transport", "transport123", "ftptest/", name, in);*/
		        
		    } catch (FileNotFoundException e) { 
		    	
		        e.printStackTrace(); 
		        
		    } 
		
	}
	
	// 在FTP服务器上生成一个文件,并将一个字符串写入到该文件中
	public void testUpLoadFromString(){
		
		try {
			
			String str = "test ftp "+ "\r\n"+ "ccccc dddd";
			
			InputStream input = new ByteArrayInputStream(str.getBytes("utf-8"));
			
			uploadFile("192.168.168.101", 21, "testftpservice", "123", "ftptest/", "test.txt", input); 
			
		} catch (UnsupportedEncodingException e) {
			
			e.printStackTrace();
			
		}
		
	}
	
	/** 
     * @Description (删除FTP上的文件)
     * 
     * @param url FTP服务器IP地址 
     * 
     * @param port FTP服务器端口 
     * 
     * @param username FTP服务器登录名 
     * 
     * @param password FTP服务器密码 
     * 
     * @param remotePath 远程文件路径 
     * 
     * @param fileName 待删除的文件名 
     * 
     * @return boolean
     */  
    public static boolean deleteFtpFile(String url, int port, String username, String password, String remotePath, String fileName){  
    	
    	boolean success = false; 
    	
        FTPClient ftp = new FTPClient(); 
        
        try { 
        	
        	int reply;  
              
            // 连接FTP服务器  
            if (port > -1)
            	
            	ftp.connect(url, port);
                
            else  
            	
                ftp.connect(url);  
              
            // 登录  
            ftp.login(username, password);  
            
            reply = ftp.getReplyCode(); 
            
            if (!FTPReply.isPositiveCompletion(reply)) {
            	
            	ftp.disconnect(); 
            	
                return success;  
            }  
              
            // 转移到FTP服务器目录  
            
            ftp.changeWorkingDirectory(remotePath);
            
            /*success = ftp.deleteFile(fileName);*/
            
            success = ftp.deleteFile(new String(fileName.getBytes("gbk"),"gbk"));
            
            ftp.logout(); 
            
        } catch (IOException e){  
        	
        	e.printStackTrace();
        	
            success = false;
            
        } finally {
        	
        	if (ftp.isConnected()) {
        		
        		try { 
        			
                    ftp.disconnect();
                    
                } catch (IOException e) {  
                	
                	e.printStackTrace();
                	
                }  
            }  
        }  
        
        return success;  
    }  
	
    public static File GetFtpFile(String url, int port, String username, String password, String remotePath, String fileName){  
    	
        FTPClient ftp = new FTPClient(); 
       
        /*File destFile = new File(fileName); */
        
        File destFile = new File(fileName); 
        
        InputStream in = null; 
        
        OutputStream out = null; 
        
        try { 
        	
        	int reply;  
              
            // 连接FTP服务器  
            if (port > -1)
            	
            	ftp.connect(url, port);
                
            else  
            	
                ftp.connect(url);  
              
            // 登录  
            ftp.login(username, password);  
            
            reply = ftp.getReplyCode(); 
            
            if (!FTPReply.isPositiveCompletion(reply)) {
            	
            	ftp.disconnect(); 
            	
            }  
             
            // 转移到FTP服务器目录  
           
            ftp.changeWorkingDirectory(remotePath);
            
            ftp.enterLocalPassiveMode();
            
            FTPFile[] fs = ftp.listFiles();  
            
            System.out.println(fs.length);
            
          /*  for (FTPFile ff : fs) {  
                //解决中文乱码问题,两次解码  
                byte[] bytes=ff.getName().getBytes("gbk");  
                String fn=new String(bytes,"gbk");  
                if (fn.equals(fileName)) {  
                    //6.写操作,将其写入到本地文件中  
                    File localFile = new File(ff.getName());  
                    
                    
                    OutputStream is = new FileOutputStream(localFile);  
                    ftp.retrieveFile(ff.getName(), is);  
                    is.close();  
                }  
            } */
            
           /* File srcFile = new File(fileName);  */
            
           /* File srcFile = new File(new String(fileName.getBytes("gbk"),"gbk"));*/
            
            int byteread = 0; // 读取的字节数
           
           /* in =  ftp.retrieveFileStream(remotePath + fileName);*/
            
            in =  ftp.retrieveFileStream(new String(fileName.getBytes("gbk"),"gbk"));
         
            
            out = new FileOutputStream(destFile);
            
            byte[] buffer = new byte[1024];  
  
            while ((byteread = in.read(buffer)) != -1) { 
            	
                out.write(buffer, 0, byteread);  
                
            }  
            
            out.flush();
            ftp.logout(); 
            
        } catch (IOException e){  
        	
        	e.printStackTrace();
        	
        } finally {
        	
        	try { 
        		
                if (out != null) 
                	
                    out.close();
                
                if (in != null) 
                	
                    in.close();
                
            } catch (IOException e) { 
            	
                e.printStackTrace(); 
                
            }
        	
        	if (ftp.isConnected()) {
        		
        		try { 
        			
                    ftp.disconnect();
                    
                } catch (IOException e) {  
                	
                	e.printStackTrace();
                	
                }  
            }  
        }  
        
        return destFile;  
    }  
	
    
	public static void main(String[] args) {
		
		FTPClientUtils clientUtils = new FTPClientUtils();
		
		Test test= new Test();
		
		File[] sources = new File[] {new File("F:/20079.txt")};
		  
		File target = new File("release_package.tar.gz");
		  
		File targetFile = test.pack(sources, target);
		  
	/*	clientUtils.testUpLoadFromDisk(targetFile,targetFile.getName());*/
		
		
		/** 删除文件 */
		/*boolean a =clientUtils.deleteFtpFile("192.168.168.101", 21, "testftpservice", "123", "ftptest/", "release_package.tar.gz");*/
		
	}
}