java FTP client


package utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.commons.net.ftp.FTPSClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;  

/** 
 *<p>ftp连接管理(使用apache commons-net-1.4.1 lib)</p> 
 * 
 * 
 */  
public class FtpUtil {
    private static final Logger logger = LoggerFactory.getLogger(FtpUtil.class);

    private static FtpUtil instance;
    private FTPClient ftpClient = null;
    private Integer timeOutSec = 10;
    private boolean isFtpsProto = false; // 是否是ftps 协议
    private String ftpUrl;  // format: ftp://192.16.1.1/path/path2 

    // 以下属性从ftpUrl中解析获得
    private String ftpHost;
    private Integer ftpPort = 21;
    private String ftpPath;
    private String userName;
    private String password;


    /** 
     * get FtpUtil 
     * @return FtpUtil 
     */  
    public synchronized FtpUtil getInstance(){  
        if( instance == null ){  
            instance = new FtpUtil(ftpUrl, userName, password);
        }
        return instance;  
    }

    public FtpUtil(String url) {
        ftpUrl = url;
        try {
            URL urlObj = new URL(url);
            isFtpsProto = "ftps".equalsIgnoreCase(urlObj.getProtocol());
            ftpHost = urlObj.getHost();

            int portTmp = urlObj.getPort();
            if (portTmp > 0) {
                ftpPort = portTmp;
            }

            ftpPath = urlObj.getPath();
            String userInfo = urlObj.getUserInfo();
            String[] splitArr = userInfo.split(":", 2);

            userName = splitArr[0];
            password = splitArr[1];
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public FtpUtil(String url, String uname, String pwd) {
        ftpUrl = url;
        try {
            URL urlObj = new URL(url);
            isFtpsProto = "ftps".equalsIgnoreCase(urlObj.getProtocol());
            ftpHost = urlObj.getHost();
            ftpPath = urlObj.getPath();

            int portTmp = urlObj.getPort();
            if (portTmp > 0) {
                ftpPort = portTmp;
            }

            userName = uname;
            password = pwd;
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /** 
     * <p>ftp登录</p> 
     * @param s_url ftp服务地址 
     * @param uname 用户名 
     * @param pass  密码 
     */  
    protected boolean login() {
        if (isFtpsProto) {
            ftpClient = new FTPSClient();
        } else {
            ftpClient = new FTPClient();  
        }

        try{  
            //连接
            ftpClient.setStrictReplyParsing(false);
            ftpClient.setConnectTimeout(timeOutSec * 1000);
            ftpClient.setDataTimeout(timeOutSec * 1000);

            ftpClient.connect(ftpHost);
            ftpClient.login(userName, password); 

            //检测连接是否成功  
            int reply = ftpClient.getReplyCode();
            if(!FTPReply.isPositiveCompletion(reply)) {
                this.closeCon();
                logger.error("FTPCONN| msg=FTP server refused connection.| reply=" + reply + "| url=" + ftpUrl);
                return false;
            }

            return ftpClient.isConnected();
        }catch(Exception ex){  
            ex.printStackTrace();
            logger.error("FTPCONN| msg=connect ftp exception| url=" + ftpUrl + "| e=" + ex.getMessage());
            //关闭  
            this.closeCon(); 
            return false;
        }
    }

    /** 
     * <p>ftp上传文件</p> 
     * @param srcUrl 须上传文件 
     * @param targetFname 生成目标文件 
     * @return true||false 
     * @throws Exception 
     */  
    public boolean uploadFile(String srcUrl, String targetFname) throws Exception{
        return uploadFile(srcUrl, ftpPath, targetFname);
    }

    public boolean uploadFile(String srcUrl, String targetPath, String targetFname) throws Exception{  
        boolean flag = false;
        if( checkConnect() ){
             File srcFile = new File(srcUrl);   
             FileInputStream fis = null;  
             try {  
                fis  = new FileInputStream(srcFile);  

                //设置上传目录
                if (!ftpClient.changeWorkingDirectory(targetPath)) {
                    ftpClient.makeDirectory(targetPath);
                    boolean chRet = ftpClient.changeWorkingDirectory(targetPath);
                    if (!chRet) {
                        throw new Exception("change ftp directory fail " + targetPath);
                    }
                }
                ftpClient.setBufferSize(1024);
                ftpClient.setControlEncoding("UTF-8");

                //设置文件类型(二进制)
                ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);  
                //上传
                flag = ftpClient.storeFile(targetFname, fis); 
            }
            /*catch (Exception e) {
                e.printStackTrace();
                logger.error("FTPUPLOAD| msg=upload file exception| url=" + ftpUrl + 
                        "| file=" + targetFname + "| e=" + e.getMessage());
            }*/
            finally{
                try {
                    this.closeCon();
                    fis.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }  
        }  
        return flag;  
    }//end method uploadFile  


    /** 
     *  
     * <p>删除ftp上的文件</p> 
     * @param srcFname 
     * @return true || false 
     */  
    public boolean removeFile(String srcFname){  
        boolean flag = false;

        if( checkConnect() ){  
            try {  
                flag = ftpClient.deleteFile(srcFname);  
            } catch (IOException e) {
                e.printStackTrace();  
            }  finally {
                this.closeCon();
            }
        }

        return flag;  
    }

    private boolean checkConnect() {
        if (null != ftpClient && ftpClient.isConnected()) {
            return true;
        }

        closeCon();
        return login();
    }

    /** 
     *<p>销毁ftp连接</p>  
     */  
    public void closeCon(){  
        if(ftpClient !=null){
            if(ftpClient.isConnected()){
                try {  
                    ftpClient.logout();  
                    ftpClient.disconnect();  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }
            }
            ftpClient = null;
        }  
    }  
}  
/latefirstcmt/19