• ftp_client_conf.properties
  1. host=192.168.72.51 
  2. port=21 
  3. userName=hundsun 
  4. password=hundsun 
  5. controlChannelKeepAlive=300 
  6. fileRootDir=d:\\uploadfiles 
  7. developModel=true 
  •  PMSFTPClient.java
  1. /** 
  2.  * Copyright (c) 2011, WWW.HUNDSUN.COM All Rights Reserved. 
  3.  */ 
  4.  
  5. package com.hundsun.pms.support; 
  6.  
  7. import java.io.File; 
  8. import java.io.FileOutputStream; 
  9. import java.io.IOException; 
  10. import java.io.InputStream; 
  11. import java.io.OutputStream; 
  12. import java.io.PrintWriter; 
  13. import java.io.UnsupportedEncodingException; 
  14. import java.net.SocketException; 
  15. import java.util.Properties; 
  16.  
  17. import org.apache.commons.logging.Log; 
  18. import org.apache.commons.logging.LogFactory; 
  19. import org.apache.commons.net.PrintCommandListener; 
  20. import org.apache.commons.net.ftp.FTP; 
  21. import org.apache.commons.net.ftp.FTPClient; 
  22. import org.apache.commons.net.ftp.FTPFile; 
  23. import org.apache.commons.net.ftp.FTPReply; 
  24.  
  25. import com.hundsun.jres.interfaces.exception.biz.JRESBizRuntimeException; 
  26. import com.ibatis.common.resources.Resources; 
  27.  
  28. /** 
  29.  * 标题:PMSFtpClient.java<br> 
  30.  * 功能说明:<br> 
  31.  * 系统版本:v1.0<br> 
  32.  * 开发人员:zhoudy@hundsun.com<br> 
  33.  * 开发时间:2012-4-9<br> 
  34.  * 功能描述:FTP客户端<br> 
  35.  */ 
  36. public class PMSFTPClient { 
  37.  
  38.     private static final Log log = LogFactory.getLog(PMSFTPClient.class); 
  39.  
  40.     private static final String PATH = "/ftp_client_conf.properties"
  41.  
  42.     private static final String HOST = "host"
  43.  
  44.     private static final String PORT = "port"
  45.  
  46.     private static final String USER_NAME = "userName"
  47.  
  48.     private static final String PASSWORD = "password"
  49.  
  50.     private static final String SEPARATOR = File.separator; 
  51.  
  52.     private static final String CONTROL_CHANNEL_KEEY_ALIVE = "controlChannelKeepAlive"
  53.  
  54.     private static final String DEVELOP_MODEL = "developModel"
  55.  
  56.     private static Properties clientConfig; 
  57.  
  58.     private FTPClient client; 
  59.  
  60.     public static void main(String[] args) throws Exception { 
  61.         // String local = "c:\\script.txt"; 
  62.         // String remote = "\\uploadfiles\\template\\script.txt"; 
  63.         // InputStream in = new FileInputStream(local); 
  64.         // PMSFTPClient ftpClient = new PMSFTPClient(); 
  65.         // ftpClient.upload(local, remote, in); 
  66.         // ftpClient.download(remote, System.out); 
  67.         // ftpClient.deleteFile(remote); 
  68.  
  69.         PMSFTPClient a = new PMSFTPClient(); 
  70.         String path = "/home/pms"
  71.         File f2 = new File("E:/pub/email/《梦幻西游》用户手册.doc"); 
  72.         OutputStream out = new FileOutputStream(f2); 
  73.         String filename2 = f2.getName(); 
  74.         System.out.println(filename2); 
  75.         // a.downFile("172.19.10.105", 21, "pms", "hundsun", 
  76.         // "pub/email/《梦幻西游》用户手册.doc", out); 
  77.     } 
  78.  
  79.     public PMSFTPClient() { 
  80.         client = new FTPClient(); 
  81.         if (clientConfig == null
  82.             clientConfig = new Properties(); 
  83.         // 初始化配置信息 
  84.         initClientConfig(); 
  85.         if (clientConfig.getProperty(DEVELOP_MODEL).trim().equals("true")) { 
  86.             // 设置将过程中使用到的命令输出到控制台 
  87.             client.addProtocolCommandListener(new PrintCommandListener( 
  88.                     new PrintWriter(System.out))); 
  89.         } 
  90.         client.setControlKeepAliveTimeout(Long.parseLong(clientConfig 
  91.                 .getProperty(CONTROL_CHANNEL_KEEY_ALIVE).trim())); 
  92.         // 连接FTP服务器 
  93.         connect(); 
  94.  
  95.     } 
  96.  
  97.     private String toIso8859(String s) { 
  98.         try { 
  99.             s = new String(s.getBytes("UTF-8"), "iso8859_1"); 
  100.         } catch (UnsupportedEncodingException e) { 
  101.             throw new JRESBizRuntimeException("-1", e.getMessage()); 
  102.  
  103.         } 
  104.         return s; 
  105.     } 
  106.  
  107.     /** 
  108.      *  
  109.      * upload:上传文件 
  110.      *  
  111.      * @param local 
  112.      *            本地要上传的文件的绝对路径 
  113.      * @param remote 
  114.      *            服务器上文件存放的相对路径 
  115.      * @param is 
  116.      *            文件流 
  117.      * @return 
  118.      * @throws 
  119.      * @since PMSFTPClient.java Ver 1.0 
  120.      *  
  121.      * @author weinh 20111029 这里做一个说明注释了remote = toIso8859(remote); 
  122.      *         把编码格式变为GBK,然后remoteFileName = new 
  123.      *         String(remoteFileName.getBytes("GBK"),"ISO-8859-1"); 
  124.      *         以上调整解决了上传中文名文件问题 
  125.      *  
  126.      *  
  127.      */ 
  128.     public boolean upload(String local, String remote, InputStream is) { 
  129.         // remote = toIso8859(remote); 
  130.         remote = remote.replaceAll("//""/"); 
  131.         // 设置PassiveMode传输 
  132.         client.enterLocalPassiveMode(); 
  133.         client.setControlEncoding("GBK"); 
  134.         // 设置以二进制流的方式传输 
  135.         try { 
  136.             client.setFileType(FTP.BINARY_FILE_TYPE); 
  137.             // 对远程目录的处理 
  138.             String remoteFileName = remote; 
  139.             if (remote.contains(SEPARATOR)) { 
  140.                 int index = remote.lastIndexOf(SEPARATOR) + 1
  141.                 remoteFileName = remote.substring(index); 
  142.                 String directory = remote.substring(0, index); 
  143.                 if (!directory.equalsIgnoreCase(SEPARATOR) 
  144.                         && !client.changeWorkingDirectory(directory)) { 
  145.                     // 如果远程目录不存在,则递归创建远程服务器目录 
  146.                     int start = 0
  147.                     int end = 0
  148.                     if (directory.startsWith(SEPARATOR)) { 
  149.                         start = 1
  150.                     } else { 
  151.                         start = 0
  152.                     } 
  153.                     end = directory.indexOf(SEPARATOR, start); 
  154.                     while (true) { 
  155.                         String subDirectory = remote.substring(start, end); 
  156.                         if (!client.changeWorkingDirectory(subDirectory)) { 
  157.                             if (client.makeDirectory(subDirectory)) { 
  158.                                 client.changeWorkingDirectory(subDirectory); 
  159.                             } else { 
  160.                                 log.error("创建目录失败"); 
  161.                                 return false
  162.                             } 
  163.                         } 
  164.                         start = end + 1
  165.                         end = directory.indexOf(SEPARATOR, start); 
  166.                         // 检查所有目录是否创建完毕 
  167.                         if (end <= start) { 
  168.                             break
  169.                         } 
  170.                     } 
  171.                 } 
  172.             } 
  173.             // 检查远程是否存在文件 
  174.             FTPFile[] files = client.listFiles(remoteFileName); 
  175.             if (files.length == 1) { 
  176.                 File f = new File(local); 
  177.                 if (files[0].getName().equals(f.getName())) { 
  178.                     // 删除服务器上文件,重新上传 
  179.                     boolean deleted = client.deleteFile(remote); 
  180.                     if (!deleted) { 
  181.                         log.error("无法删除已经上传过的同名文件!"); 
  182.                         return false
  183.                     } 
  184.                 } 
  185.                 // 尝试移动文件内读取指针,实现断点续传 
  186.                 /* 
  187.                  * if (is.skip(remoteSize) == remoteSize) { 
  188.                  * client.setRestartOffset(remoteSize); if 
  189.                  * (client.storeFile(remote, is)) { log.info("断点续传成功!"); return 
  190.                  * true; } } 
  191.                  */ 
  192.             } 
  193.             remoteFileName = new String(remoteFileName.getBytes("GBK"), 
  194.                     "ISO-8859-1"); 
  195.             if (client.storeFile(remoteFileName, is)) { 
  196.                 log.info("上传成功!"); 
  197.                 return true
  198.             } else { 
  199.                 log.error("上传失败!"); 
  200.                 return false
  201.             } 
  202.  
  203.         } catch (IOException e) { 
  204.             log.error(e.getMessage()); 
  205.             throw new JRESBizRuntimeException("-1", e.getMessage()); 
  206.         } finally { 
  207.             try { 
  208.                 is.close(); 
  209.             } catch (IOException e) { 
  210.                 log.error(e.getMessage()); 
  211.                 throw new JRESBizRuntimeException("-1", e.getMessage()); 
  212.             } 
  213.         } 
  214.     } 
  215.  
  216.     /** 
  217.      *  
  218.      * download:下载文件 
  219.      *  
  220.      * @param remote 
  221.      *            文件相对路径 
  222.      * @param out 
  223.      * @return 
  224.      * @throws 
  225.      * @since PMSFTPClient.java Ver 1.0 
  226.      */ 
  227.     public boolean download(String remote, OutputStream out) { 
  228.         // remote = toIso8859(remote); 
  229.         boolean result = true
  230.         client.enterLocalPassiveMode(); 
  231.         client.setControlEncoding("GBK"); 
  232.         try { 
  233.             client.setFileType(FTP.BINARY_FILE_TYPE); 
  234.             remote = new String(remote.getBytes("GBK"), "ISO-8859-1"); 
  235.             result = client.retrieveFile(remote, out); 
  236.         } catch (IOException e) { 
  237.             log.error(e.getMessage()); 
  238.             throw new JRESBizRuntimeException("-1", e.getMessage()); 
  239.         } finally { 
  240.             try { 
  241.                 out.flush(); 
  242.                 out.close(); 
  243.             } catch (IOException e) { 
  244.                 log.error(e.getMessage()); 
  245.                 throw new JRESBizRuntimeException("-1", e.getMessage()); 
  246.  
  247.             } 
  248.         } 
  249.         return result; 
  250.     } 
  251.  
  252.     public FTPFile[] getFiles(String remote, OutputStream out) { 
  253.         remote = toIso8859(remote); 
  254.         client.enterLocalPassiveMode(); 
  255.         client.setControlEncoding("UTF-8"); 
  256.         try { 
  257.             client.setFileType(FTP.BINARY_FILE_TYPE); 
  258.             return client.listFiles(); 
  259.         } catch (IOException e) { 
  260.             log.error(e.getMessage()); 
  261.             throw new JRESBizRuntimeException("-1", e.getMessage()); 
  262.         } finally { 
  263.             try { 
  264.                 out.close(); 
  265.             } catch (IOException e) { 
  266.                 log.error(e.getMessage()); 
  267.                 throw new JRESBizRuntimeException("-1", e.getMessage()); 
  268.  
  269.             } 
  270.         } 
  271.     } 
  272.  
  273.     /** 
  274.      *  
  275.      * deleteFile:删除文件 
  276.      *  
  277.      * @param remote 
  278.      *            要删除的文件路径 
  279.      * @return 
  280.      * @throws 
  281.      * @since PMSFTPClient.java Ver 1.0 
  282.      */ 
  283.     public boolean deleteFile(String remote) { 
  284.         try { 
  285.             remote = toIso8859(remote); 
  286.             boolean t = client.deleteFile(remote); 
  287.             if (t) { 
  288.                 log.info(remote + " 删除成功!"); 
  289.             } else { 
  290.                 log.info(remote + " 删除失败"); 
  291.             } 
  292.             return t; 
  293.  
  294.         } catch (IOException e) { 
  295.             log.error(e.getMessage()); 
  296.             throw new JRESBizRuntimeException("-1", e.getMessage()); 
  297.         } 
  298.     } 
  299.  
  300.     private boolean connect() { 
  301.         int port = 0
  302.         try { 
  303.             port = Integer.valueOf(clientConfig.getProperty(PORT).trim()); 
  304.             client.connect(clientConfig.getProperty(HOST).trim(), port); 
  305.             if (FTPReply.isPositiveCompletion(client.getReplyCode())) { 
  306.                 boolean b = client.login(clientConfig.getProperty(USER_NAME) 
  307.                         .trim(), clientConfig.getProperty(PASSWORD).trim()); 
  308.                 if (b) { 
  309.                     log.info("账户:" + clientConfig.getProperty(USER_NAME).trim() 
  310.                             + " 成功连接到FTP服务器!"); 
  311.                     return true
  312.                 } 
  313.                 return false
  314.             } 
  315.             disconnect(); 
  316.             return false
  317.         } catch (NumberFormatException e) { 
  318.             log.error(e.getMessage()); 
  319.             throw new JRESBizRuntimeException("-1""端口" + port + "连接失败,原因是:" 
  320.                     + e.getMessage()); 
  321.         } catch (SocketException e) { 
  322.             log.error(e.getMessage()); 
  323.             throw new JRESBizRuntimeException("-1""与ftp 服务器通信失败,原因是:" 
  324.                     + e.getMessage()); 
  325.  
  326.         } catch (IOException e) { 
  327.             log.error(e.getMessage()); 
  328.             throw new JRESBizRuntimeException("-1", e.getMessage()); 
  329.  
  330.         } 
  331.     } 
  332.  
  333.     private void disconnect() { 
  334.         if (client.isConnected()) { 
  335.             try { 
  336.                 client.disconnect(); 
  337.             } catch (IOException e) { 
  338.                 log.error(e.getMessage()); 
  339.                 throw new JRESBizRuntimeException("-1", e.getMessage()); 
  340.  
  341.             } 
  342.         } 
  343.     } 
  344.  
  345.     private void initClientConfig() { 
  346.         InputStream in = null
  347.         try { 
  348.             in = Resources.getResourceAsStream(PATH); 
  349.             clientConfig.load(in); 
  350.             // in = new 
  351.             // FileInputStream("D:\\workspace\\PMS\\src\\ftp_client_conf.properties"); 
  352.         } catch (IOException e1) { 
  353.             log.error(e1.getMessage()); 
  354.             throw new JRESBizRuntimeException("-1"
  355.                     "读取配置文件ftp_client_conf.properties失败,原因是:" + e1.getMessage()); 
  356.         } 
  357.     } 
  358.  
  359.     /* 
  360.      * public boolean downFile(String ip, int port, String username, String 
  361.      * password, String fileName, OutputStream outputStream) { boolean success = 
  362.      * false; FTPClient ftp = new FTPClient(); try { ftp.connect(ip, port); // 
  363.      * 下面三行代码必须要,而且不能改变编码格式 ftp.setControlEncoding("GBK"); // 
  364.      * 如果采用默认端口,可以使用ftp.connect(url) 的方式直接连接FTP服务器 ftp.login(username, 
  365.      * password);// 登录 ftp.setFileType(FTPClient.BINARY_FILE_TYPE); 
  366.      * System.out.println("登陆成功。。。。"); download(ftp, fileName, outputStream); // 
  367.      * System.out.println(fileName); // fileName = new 
  368.      * String(fileName.getBytes("GBK"), "ISO-8859-1"); // 
  369.      * ftp.retrieveFile(fileName, outputStream); // 
  370.      * System.out.println(fileName); // outputStream.flush(); // 
  371.      * outputStream.close(); ftp.logout(); success = true; } catch (IOException 
  372.      * e) { e.printStackTrace(); } finally { if (ftp.isConnected()) { try { 
  373.      * ftp.disconnect(); } catch (IOException ioe) { } } } return success; } 
  374.      */