Ftp Client

  • 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.  * 開發人員:[email protected]<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.      */ 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章