天天看点

Ftp Client

ftp_client_conf.properties

host=192.168.72.51 

port=21 

userName=hundsun 

password=hundsun 

controlChannelKeepAlive=300 

fileRootDir=d:\\uploadfiles 

developModel=true 

 PMSFTPClient.java

/** 

 * Copyright (c) 2011, WWW.HUNDSUN.COM All Rights Reserved. 

 */ 

package com.hundsun.pms.support; 

import java.io.File; 

import java.io.FileOutputStream; 

import java.io.IOException; 

import java.io.InputStream; 

import java.io.OutputStream; 

import java.io.PrintWriter; 

import java.io.UnsupportedEncodingException; 

import java.net.SocketException; 

import java.util.Properties; 

import org.apache.commons.logging.Log; 

import org.apache.commons.logging.LogFactory; 

import org.apache.commons.net.PrintCommandListener; 

import org.apache.commons.net.ftp.FTP; 

import org.apache.commons.net.ftp.FTPClient; 

import org.apache.commons.net.ftp.FTPFile; 

import org.apache.commons.net.ftp.FTPReply; 

import com.hundsun.jres.interfaces.exception.biz.JRESBizRuntimeException; 

import com.ibatis.common.resources.Resources; 

 * 标题:PMSFtpClient.java<br> 

 * 功能说明:<br> 

 * 系统版本:v1.0<br> 

 * 开发人员:[email protected]<br> 

 * 开发时间:2012-4-9<br> 

 * 功能描述:FTP客户端<br> 

public class PMSFTPClient { 

    private static final Log log = LogFactory.getLog(PMSFTPClient.class); 

    private static final String PATH = "/ftp_client_conf.properties"; 

    private static final String HOST = "host"; 

    private static final String PORT = "port"; 

    private static final String USER_NAME = "userName"; 

    private static final String PASSWORD = "password"; 

    private static final String SEPARATOR = File.separator; 

    private static final String CONTROL_CHANNEL_KEEY_ALIVE = "controlChannelKeepAlive"; 

    private static final String DEVELOP_MODEL = "developModel"; 

    private static Properties clientConfig; 

    private FTPClient client; 

    public static void main(String[] args) throws Exception { 

        // String local = "c:\\script.txt"; 

        // String remote = "\\uploadfiles\\template\\script.txt"; 

        // InputStream in = new FileInputStream(local); 

        // PMSFTPClient ftpClient = new PMSFTPClient(); 

        // ftpClient.upload(local, remote, in); 

        // ftpClient.download(remote, System.out); 

        // ftpClient.deleteFile(remote); 

        PMSFTPClient a = new PMSFTPClient(); 

        String path = "/home/pms"; 

        File f2 = new File("E:/pub/email/《梦幻西游》用户手册.doc"); 

        OutputStream out = new FileOutputStream(f2); 

        String filename2 = f2.getName(); 

        System.out.println(filename2); 

        // a.downFile("172.19.10.105", 21, "pms", "hundsun", 

        // "pub/email/《梦幻西游》用户手册.doc", out); 

    } 

    public PMSFTPClient() { 

        client = new FTPClient(); 

        if (clientConfig == null) 

            clientConfig = new Properties(); 

        // 初始化配置信息 

        initClientConfig(); 

        if (clientConfig.getProperty(DEVELOP_MODEL).trim().equals("true")) { 

            // 设置将过程中使用到的命令输出到控制台 

            client.addProtocolCommandListener(new PrintCommandListener( 

                    new PrintWriter(System.out))); 

        } 

        client.setControlKeepAliveTimeout(Long.parseLong(clientConfig 

                .getProperty(CONTROL_CHANNEL_KEEY_ALIVE).trim())); 

        // 连接FTP服务器 

        connect(); 

    private String toIso8859(String s) { 

        try { 

            s = new String(s.getBytes("UTF-8"), "iso8859_1"); 

        } catch (UnsupportedEncodingException e) { 

            throw new JRESBizRuntimeException("-1", e.getMessage()); 

        return s; 

    /** 

     *  

     * upload:上传文件 

     * @param local 

     *            本地要上传的文件的绝对路径 

     * @param remote 

     *            服务器上文件存放的相对路径 

     * @param is 

     *            文件流 

     * @return 

     * @throws 

     * @since PMSFTPClient.java Ver 1.0 

     * @author weinh 20111029 这里做一个说明注释了remote = toIso8859(remote); 

     *         把编码格式变为GBK,然后remoteFileName = new 

     *         String(remoteFileName.getBytes("GBK"),"ISO-8859-1"); 

     *         以上调整解决了上传中文名文件问题 

     */ 

    public boolean upload(String local, String remote, InputStream is) { 

        // remote = toIso8859(remote); 

        remote = remote.replaceAll("//", "/"); 

        // 设置PassiveMode传输 

        client.enterLocalPassiveMode(); 

        client.setControlEncoding("GBK"); 

        // 设置以二进制流的方式传输 

            client.setFileType(FTP.BINARY_FILE_TYPE); 

            // 对远程目录的处理 

            String remoteFileName = remote; 

            if (remote.contains(SEPARATOR)) { 

                int index = remote.lastIndexOf(SEPARATOR) + 1; 

                remoteFileName = remote.substring(index); 

                String directory = remote.substring(0, index); 

                if (!directory.equalsIgnoreCase(SEPARATOR) 

                        && !client.changeWorkingDirectory(directory)) { 

                    // 如果远程目录不存在,则递归创建远程服务器目录 

                    int start = 0; 

                    int end = 0; 

                    if (directory.startsWith(SEPARATOR)) { 

                        start = 1; 

                    } else { 

                        start = 0; 

                    } 

                    end = directory.indexOf(SEPARATOR, start); 

                    while (true) { 

                        String subDirectory = remote.substring(start, end); 

                        if (!client.changeWorkingDirectory(subDirectory)) { 

                            if (client.makeDirectory(subDirectory)) { 

                                client.changeWorkingDirectory(subDirectory); 

                            } else { 

                                log.error("创建目录失败"); 

                                return false; 

                            } 

                        } 

                        start = end + 1; 

                        end = directory.indexOf(SEPARATOR, start); 

                        // 检查所有目录是否创建完毕 

                        if (end <= start) { 

                            break; 

                } 

            } 

            // 检查远程是否存在文件 

            FTPFile[] files = client.listFiles(remoteFileName); 

            if (files.length == 1) { 

                File f = new File(local); 

                if (files[0].getName().equals(f.getName())) { 

                    // 删除服务器上文件,重新上传 

                    boolean deleted = client.deleteFile(remote); 

                    if (!deleted) { 

                        log.error("无法删除已经上传过的同名文件!"); 

                        return false; 

                // 尝试移动文件内读取指针,实现断点续传 

                /* 

                 * if (is.skip(remoteSize) == remoteSize) { 

                 * client.setRestartOffset(remoteSize); if 

                 * (client.storeFile(remote, is)) { log.info("断点续传成功!"); return 

                 * true; } } 

                 */ 

            remoteFileName = new String(remoteFileName.getBytes("GBK"), 

                    "ISO-8859-1"); 

            if (client.storeFile(remoteFileName, is)) { 

                log.info("上传成功!"); 

                return true; 

            } else { 

                log.error("上传失败!"); 

                return false; 

        } catch (IOException e) { 

            log.error(e.getMessage()); 

        } finally { 

            try { 

                is.close(); 

            } catch (IOException e) { 

                log.error(e.getMessage()); 

                throw new JRESBizRuntimeException("-1", e.getMessage()); 

     * download:下载文件 

     *            文件相对路径 

     * @param out 

    public boolean download(String remote, OutputStream out) { 

        boolean result = true; 

            remote = new String(remote.getBytes("GBK"), "ISO-8859-1"); 

            result = client.retrieveFile(remote, out); 

                out.flush(); 

                out.close(); 

        return result; 

    public FTPFile[] getFiles(String remote, OutputStream out) { 

        remote = toIso8859(remote); 

        client.setControlEncoding("UTF-8"); 

            return client.listFiles(); 

     * deleteFile:删除文件 

     *            要删除的文件路径 

    public boolean deleteFile(String remote) { 

            remote = toIso8859(remote); 

            boolean t = client.deleteFile(remote); 

            if (t) { 

                log.info(remote + " 删除成功!"); 

                log.info(remote + " 删除失败"); 

            return t; 

    private boolean connect() { 

        int port = 0; 

            port = Integer.valueOf(clientConfig.getProperty(PORT).trim()); 

            client.connect(clientConfig.getProperty(HOST).trim(), port); 

            if (FTPReply.isPositiveCompletion(client.getReplyCode())) { 

                boolean b = client.login(clientConfig.getProperty(USER_NAME) 

                        .trim(), clientConfig.getProperty(PASSWORD).trim()); 

                if (b) { 

                    log.info("账户:" + clientConfig.getProperty(USER_NAME).trim() 

                            + " 成功连接到FTP服务器!"); 

                    return true; 

            disconnect(); 

            return false; 

        } catch (NumberFormatException e) { 

            throw new JRESBizRuntimeException("-1", "端口" + port + "连接失败,原因是:" 

                    + e.getMessage()); 

        } catch (SocketException e) { 

            throw new JRESBizRuntimeException("-1", "与ftp 服务器通信失败,原因是:" 

    private void disconnect() { 

        if (client.isConnected()) { 

                client.disconnect(); 

    private void initClientConfig() { 

        InputStream in = null; 

            in = Resources.getResourceAsStream(PATH); 

            clientConfig.load(in); 

            // in = new 

            // FileInputStream("D:\\workspace\\PMS\\src\\ftp_client_conf.properties"); 

        } catch (IOException e1) { 

            log.error(e1.getMessage()); 

            throw new JRESBizRuntimeException("-1", 

                    "读取配置文件ftp_client_conf.properties失败,原因是:" + e1.getMessage()); 

    /* 

     * public boolean downFile(String ip, int port, String username, String 

     * password, String fileName, OutputStream outputStream) { boolean success = 

     * false; FTPClient ftp = new FTPClient(); try { ftp.connect(ip, port); // 

     * 下面三行代码必须要,而且不能改变编码格式 ftp.setControlEncoding("GBK"); // 

     * 如果采用默认端口,可以使用ftp.connect(url) 的方式直接连接FTP服务器 ftp.login(username, 

     * password);// 登录 ftp.setFileType(FTPClient.BINARY_FILE_TYPE); 

     * System.out.println("登陆成功。。。。"); download(ftp, fileName, outputStream); // 

     * System.out.println(fileName); // fileName = new 

     * String(fileName.getBytes("GBK"), "ISO-8859-1"); // 

     * ftp.retrieveFile(fileName, outputStream); // 

     * System.out.println(fileName); // outputStream.flush(); // 

     * outputStream.close(); ftp.logout(); success = true; } catch (IOException 

     * e) { e.printStackTrace(); } finally { if (ftp.isConnected()) { try { 

     * ftp.disconnect(); } catch (IOException ioe) { } } } return success; } 

     本文转自danni505 51CTO博客,原文链接:http://blog.51cto.com/danni505/830446,如需转载请自行联系原作者