用FTPClient对ftp文件进行上传下载等操作


[java]  view plain copy print ?
  1. package com.ad.util;  
  2.   
  3. import org.apache.commons.net.ftp.FTP;  
  4. import org.apache.commons.net.ftp.FTPClient;  
  5. import org.apache.commons.net.ftp.FTPReply;  
  6. import org.apache.commons.net.ftp.FTPFile;  
  7. import org.apache.commons.net.ftp.FTPListParseEngine;  
  8.   
  9. import com.ad.adweb.system.GlobalConst;  
  10.   
  11. import java.io.InputStream;  
  12. import java.io.FileOutputStream;  
  13. import java.io.File;  
  14. import java.util.Calendar;  
  15.   
  16. /** 
  17.  * <p> 
  18.  * Title: FTPUtil 
  19.  * </p> 
  20.  * <p> 
  21.  * Description: FTP操作的工具类,通过此类可以完成文件到指定FTP服务器的上传和下载。 
  22.  * </p> 
  23.  * <p> 
  24.  * Copyright: Copyright (c) 2007 
  25.  * </p> 
  26.  * <p> 
  27.  * Company: Routon 
  28.  * </p> 
  29.  *  
  30.  * @author zhihui zhou 
  31.  * @version 1.0 InternalError-->Exception by jiangyl 
  32.  * @2007.12.21 
  33.  */  
  34. public class FTPUtil  
  35. {  
  36.    
  37.     /** 
  38.      * 全局配置项: ftp传输模式: passive/active 
  39.      */  
  40.     //private static String ConfigFtpMode = null;  
  41.   
  42.     /** 
  43.      * 全局配置项: applet ftp传输模式: passive/active 
  44.      */  
  45.     //private static String ConfigClientFtpMode = null;  
  46.   
  47.     /** 
  48.      * ftp服务器的ip地址 
  49.      */  
  50.     private String              _ftpServer;  
  51.   
  52.     /** 
  53.      * ftp端口 
  54.      */  
  55.     private int                     _ftpPort;  
  56.   
  57.     //   
  58.     /** 
  59.      * ftp服务器的有效登陆用户名 
  60.      */  
  61.     private String              _userName;  
  62.   
  63.     /** 
  64.      * ftp服务器的有效登陆用户密码 
  65.      */  
  66.     private String              _password;  
  67.   
  68.     /** 
  69.      * ftp客户端的对象实例 
  70.      */  
  71.     private FTPClient           _ftp;  
  72.   
  73.     /** 
  74.      * ftp mode 
  75.      */  
  76.     private String              FtpMode = null;  
  77.   
  78.       
  79.     // public FTPUtil(String ftpServer, String userName, String password) throws Exception  
  80.     // {  
  81.     // try  
  82.     // {  
  83.     // setFTPServer(ftpServer);  
  84.     // setUserName(userName);  
  85.     // setPassword(password);  
  86.     //  
  87.     // // 初始化ftp客户端对象实例  
  88.     // _ftp = new FTPClient();  
  89.     // }  
  90.     // catch (Exception ex)  
  91.     // {  
  92.     // throw new Exception(ex.getMessage());  
  93.     // }  
  94.     // }  
  95.     /** 
  96.      * 构造器 
  97.      *  
  98.      * @param ftpServer FTP服务器 
  99.      *          String 
  100.      * @param userName 用户名 
  101.      *          String 
  102.      * @param password 密码 
  103.      *          String 
  104.      * @throws Exception 异常 
  105.      */  
  106.     public FTPUtil(String ftpServer, int port, String userName, String password) throws Exception  
  107.     {  
  108.         try  
  109.         {  
  110.             setFTPServer(ftpServer);  
  111.             setUserName(userName);  
  112.             setPassword(password);  
  113.             this._ftpPort = port;  
  114.   
  115.             // 初始化ftp客户端对象实例  
  116.             _ftp = new FTPClient();  
  117.         }  
  118.         catch (Exception ex)  
  119.         {  
  120.             throw new Exception(ex.getMessage());  
  121.         }  
  122.     }  
  123.   
  124.     /** 
  125.      * 获取ftp服务器的ip地址 
  126.      *  
  127.      * @return ftpServerIP String 
  128.      */  
  129.     public String getFTPServer()  
  130.     {  
  131.         return _ftpServer;  
  132.     }  
  133.   
  134.     /** 
  135.      * 设置ftp服务器的ip地址 
  136.      *  
  137.      * @param ftpServerIP 
  138.      *          String 
  139.      * @throws Exception 
  140.      */  
  141.     public void setFTPServer(String ftpServer) throws Exception  
  142.     {  
  143.         // 检查输入的ftp服务器地址,不允许为空。  
  144.         if (ftpServer == null || ftpServer.length() == 0)  
  145.         {  
  146.             throw new Exception("ftp服务器的IP地址不能够为空。");  
  147.         }  
  148.   
  149.         _ftpServer = ftpServer;  
  150.     }  
  151.   
  152.     /** 
  153.      * 获取ftp服务器的用户名 
  154.      *  
  155.      * @return userName String 
  156.      */  
  157.     public String getUserName()  
  158.     {  
  159.         return _userName;  
  160.     }  
  161.   
  162.     /** 
  163.      * 设置ftp服务器的用户名 
  164.      *  
  165.      * @param userName 
  166.      *          String 
  167.      * @throws Exception 
  168.      */  
  169.     public void setUserName(String userName) throws Exception  
  170.     {  
  171.         // 检查输入的ftp服务器名称,不允许为空。  
  172.         if (userName == null || userName.length() == 0)  
  173.         {  
  174.             throw new Exception("ftp服务器的登陆用户名不能够为空。");  
  175.         }  
  176.   
  177.         _userName = userName;  
  178.     }  
  179.   
  180.     /** 
  181.      * 获取ftp服务器的用户登陆密码 
  182.      *  
  183.      * @return password String 
  184.      */  
  185.     public String getPassword()  
  186.     {  
  187.         return _password;  
  188.     }  
  189.   
  190.     /** 
  191.      * 设置ftp服务器的用户密码 
  192.      *  
  193.      * @param password 
  194.      *          String 
  195.      * @throws Exception 
  196.      */  
  197.     public void setPassword(String password) throws Exception  
  198.     {  
  199.         // 检查输入的ftp服务器用户登陆密码,不允许为空。  
  200.         if (password == null || password.length() == 0)  
  201.         {  
  202.             throw new Exception("ftp服务器的登陆用户密码不能够为空。");  
  203.         }  
  204.   
  205.         _password = password;  
  206.     }  
  207.   
  208.     /** 
  209.      * 上传文件到ftp服务器的指定路径 
  210.      *  
  211.      * @param ftpPath 
  212.      *          文件上传到ftp的路径 
  213.      * @param inputStream 
  214.      *          待上传的文件流 
  215.      * @return isUploadSuccessed ture表示上传成功,发了社表明上传失败。 
  216.      * @throws Exception 
  217.      */  
  218.     public boolean UploadFile(String ftpPath, InputStream inputSteam) throws Exception  
  219.     {  
  220.         boolean isSuccessed = false;  
  221.   
  222.         // 通过指定的用户名和密码登陆ftp服务器  
  223.         try  
  224.         {  
  225.             if (Login(_userName, _password))  
  226.             {  
  227.                 // 开始上传文件  
  228.                 _ftp.setFileType(FTP.BINARY_FILE_TYPE);  
  229.   
  230.                 if (_ftp.storeFile(ftpPath, inputSteam))  
  231.                 {  
  232.                     isSuccessed = true;  
  233.                 }  
  234.                 else  
  235.                 {  
  236.                     throw new Exception("文件上传失败!");  
  237.                 }  
  238.             }  
  239.             else  
  240.             {  
  241.                 // 登陆失败  
  242.                 isSuccessed = false;  
  243.                 throw new Exception("用户" + _userName + "登陆ftp服务器" + _password + "失败。");  
  244.             }  
  245.         }  
  246.         catch (Exception ex)  
  247.         {  
  248.             throw new Exception(ex.getMessage());  
  249.         }  
  250.         finally  
  251.         {  
  252.             ftpDispose();  
  253.         }  
  254.   
  255.         return isSuccessed;  
  256.     }  
  257.   
  258.     /** 
  259.      * 在ftp服务器上面创建一个目录 
  260.      *  
  261.      * @param folderName 
  262.      *          目录名称 
  263.      * @return boolean 创建结果true表示成功,false表示失败 
  264.      * @throws Exception 
  265.      */  
  266.     public boolean CreateFolder(String folderName) throws Exception  
  267.     {  
  268.         boolean isSuccessed = false;  
  269.   
  270.         // 通过指定的用户名和密码登陆ftp服务器  
  271.         try  
  272.         {  
  273.             if (Login(_userName, _password))  
  274.             {  
  275.                 // 开始创建指定的目录到ftp服务器上  
  276.                 if (_ftp.makeDirectory(folderName))  
  277.                 {  
  278.                     isSuccessed = true;  
  279.                 }  
  280.                 else  
  281.                 {  
  282.                     throw new Exception("ftp文件夹创建失败!");  
  283.                 }  
  284.             }  
  285.             else  
  286.             {  
  287.                 // 登陆ftp失败  
  288.                 isSuccessed = false;  
  289.                 throw new Exception("用户" + _userName + "登陆ftp服务器" + _password + "失败。");  
  290.             }  
  291.         }  
  292.         catch (Exception ex)  
  293.         {  
  294.             throw new Exception(ex.getMessage());  
  295.         }  
  296.         finally  
  297.         {  
  298.             ftpDispose();  
  299.         }  
  300.   
  301.         return isSuccessed;  
  302.     }  
  303.   
  304.     /** 
  305.      * 根据指定的用户名和密码登陆ftp服务器 
  306.      *  
  307.      * @param username 
  308.      *          登陆用户名 
  309.      * @param password 
  310.      *          登陆用户密码 
  311.      * @return isUploadSuccessed true表示登陆成功,false表示登陆失败 
  312.      * @throws Exception 
  313.      */  
  314.     public boolean Login(String username, String password) throws Exception  
  315.     {  
  316.         boolean isSuccessed = false;  
  317.   
  318.         try  
  319.         {  
  320.             int reply = 0;  
  321.   
  322.             // 连接到指定的ftp服务器  
  323.             _ftp.connect(_ftpServer, this._ftpPort);  
  324.   
  325.             // 检查ftp连接请求的响应码,确保本次连接请求是成功还是失败。  
  326.             reply = _ftp.getReplyCode();  
  327.             if (!FTPReply.isPositiveCompletion(reply))  
  328.             {  
  329.                 _ftp.disconnect();  
  330.                 throw new Exception("FTP服务器拒绝了连接.");  
  331.             }  
  332.   
  333.             // 根据指定的用户名和密码登陆ftp服务器  
  334.             if (!_ftp.login(_userName, _password))  
  335.             {  
  336.                 throw new Exception("用户" + _userName + "登陆ftp服务器" + _password + "失败。");  
  337.             }  
  338.   
  339.             // set ftp mode  
  340.             setCurrentFtpMode();  
  341.   
  342.             isSuccessed = true;  
  343.         }  
  344.         catch (Exception e)  
  345.         {  
  346.             throw new Exception(e.getMessage());  
  347.         }  
  348.   
  349.         return isSuccessed;  
  350.     }  
  351.   
  352.     /** 
  353.      * 设置ftp模式,优先顺序: 1. FtpMode 2. ConfigFtpMode 3. commons-net lib 默认 
  354.      */  
  355.     private void setCurrentFtpMode()  
  356.     {  
  357.         String tmpFtpMode = null;  
  358.         if (FtpMode != null && FtpMode.length() > 0)  
  359.         {  
  360.             tmpFtpMode = FtpMode;  
  361.         }  
  362.         else if (GlobalConst.ConfigFtpMode != null && GlobalConst.ConfigFtpMode.length() > 0)  
  363.         {  
  364.             tmpFtpMode = GlobalConst.ConfigFtpMode;  
  365.         }  
  366.   
  367.         if (tmpFtpMode != null && tmpFtpMode.length() > 0)  
  368.         {  
  369.             if (tmpFtpMode.equalsIgnoreCase("passive"))  
  370.             {  
  371.                 _ftp.enterLocalPassiveMode();  
  372.             }  
  373.             else if (tmpFtpMode.equalsIgnoreCase("active"))  
  374.             {  
  375.                 _ftp.enterLocalActiveMode();  
  376.             }  
  377.         }  
  378.     }  
  379.   
  380.     /** 
  381.      * 释放ftp客户端 
  382.      */  
  383.     public void ftpDispose()  
  384.     {  
  385.         try  
  386.         {  
  387.             // 注销FTP客户端  
  388.             _ftp.logout();  
  389.         }  
  390.         catch (Exception e)  
  391.         {  
  392.             // 如果FTP注销失败什么也不做,忽略掉异常。  
  393.         }  
  394.   
  395.         // 如果FTP客户端的连接还存在则断开连接。  
  396.         if (_ftp.isConnected())  
  397.         {  
  398.             try  
  399.             {  
  400.                 _ftp.disconnect();  
  401.             }  
  402.             catch (Exception ex)  
  403.             {  
  404.                 // 如果断开FTP连接失败什么也不做,忽略掉异常。  
  405.             }  
  406.         }  
  407.     }  
  408.   
  409.     /** 
  410.      * 从ftp下载文件 
  411.      *  
  412.      * @param FtpFileName 
  413.      *          来源文件名称 
  414.      * @param LocaFileName 
  415.      *          目的文件名称 
  416.      * @return boolean true表示下载文件成功,false表示下载文件失败 
  417.      * @throws Exception 
  418.      */  
  419.     public boolean DownFile(String FtpFileName, String LocaFileName) throws Exception  
  420.     {  
  421.         boolean isSuccessed = false;  
  422.   
  423.         try  
  424.         {  
  425.             if (Login(_userName, _password))  
  426.             {  
  427.                 File file = new File(LocaFileName);  
  428.                 FileOutputStream fos = new FileOutputStream(file);  
  429.   
  430.                 // + by jiangyl @2008.7.6  
  431.                 _ftp.setFileType(FTP.BINARY_FILE_TYPE);  
  432.   
  433.                 isSuccessed = _ftp.retrieveFile(FtpFileName, fos);  
  434.                 fos.close();  
  435.                 file = null;  
  436.   
  437.                 if (!isSuccessed)  
  438.                 {  
  439.                     throw new Exception("文件" + FtpFileName + "下载失败.");  
  440.                 }  
  441.             }  
  442.             else  
  443.             {  
  444.                 isSuccessed = false;  
  445.                 throw new Exception("用户" + _userName + "登陆ftp服务器" + _password + "失败。");  
  446.             }  
  447.         }  
  448.         catch (Exception ex)  
  449.         {  
  450.             throw new Exception(ex.getMessage());  
  451.         }  
  452.         finally  
  453.         {  
  454.             ftpDispose();  
  455.         }  
  456.   
  457.         return isSuccessed;  
  458.     }  
  459.   
  460.     /** 
  461.      * 提供一静态方法,由外部定时任务模块调用,对FTP服务器上的过期数据文件进行清理 
  462.      *  
  463.      * @return int 表示成功删除文件的个数 
  464.      * @throws Exception 
  465.      */  
  466.     public static void ClearFTPExpiredFiles() throws Exception  
  467.     {  
  468.         com.ad.util.FtpServerInfo ftpServer = com.ad.util.FtpServerInfo.getInstance();  
  469.         com.ad.util.FTPUtil ftpUtil = new com.ad.util.FTPUtil(ftpServer.getFtp().getFtpIntIP(),  
  470.             ftpServer.getFtp().getPort(), ftpServer.getFtp().getUpName(), ftpServer.getFtp().getUpPWD());  
  471.   
  472.         ftpUtil.ClearExpiredFiles();  
  473.     }  
  474.   
  475.     /** 
  476.      * 根据web.xml中配置, 对FTP服务器上的过期数据文件进行清理,清理的目录有:playbill、terParam、theme、ThemePolicy 
  477.      *  
  478.      * @return int 表示成功删除文件的个数 
  479.      * @throws Exception 
  480.      */  
  481.     public int ClearExpiredFiles() throws Exception  
  482.     {  
  483.           
  484.         int deleteNum = 0;  
  485.   
  486.         try  
  487.         {  
  488.             if (Login(_userName, _password))  
  489.             {  
  490.                 deleteNum += DeleteExpiredFiles("playbill");  
  491.                 deleteNum += DeleteExpiredFiles("terParam");  
  492.                 deleteNum += DeleteExpiredFiles("theme");  
  493.                 deleteNum += DeleteExpiredFiles("ThemePolicy");  
  494.             }  
  495.             else  
  496.             {  
  497.                   
  498.                 throw new Exception("用户" + _userName + "登陆ftp服务器" + _password + "失败。");  
  499.             }  
  500.         }  
  501.         catch (Exception ex)  
  502.         {  
  503.             throw new Exception(ex.getMessage());  
  504.         }  
  505.         finally  
  506.         {  
  507.             ftpDispose();  
  508.         }  
  509.   
  510.         return deleteNum;  
  511.     }  
  512.   
  513.     /** 
  514.      * 根据web.xml中配置, 对FTP服务器上的过期数据文件进行清理 
  515.      *  
  516.      * @param FtpPathName 
  517.      *          待清理的目录 
  518.      * @return int 表示成功删除文件的个数 
  519.      * @throws Exception 
  520.      */  
  521.     private int DeleteExpiredFiles(String FtpPathName) throws Exception  
  522.     {  
  523.         boolean isSuccessed = false;  
  524.         int deleteNum = 0;  
  525.         Calendar dtNow = Calendar.getInstance();  
  526.         Calendar dt = null;  
  527.         FTPFile[] files = null;  
  528.         long t1 = System.currentTimeMillis();  
  529.         long t2 = -1;  
  530.           
  531.         try  
  532.         {  
  533.             // _ftp.changeWorkingDirectory("ThemePolicy");  
  534.             // String[] names = _ftp.listNames();  
  535.   
  536.             // Paged access, using a parser accessible by auto-detect:  
  537.             FTPListParseEngine engine = _ftp.initiateListParsing(FtpPathName);  
  538.               
  539.             while (engine.hasNext())  
  540.             {  
  541.                 files = engine.getNext(25); // "page size" you want  
  542.   
  543.                 for (int i = 0; i < files.length; i++)  
  544.                 {  
  545.                     // System.out.println(files[i].getName()+" -- "+FastDateFormat.getInstance("yyyy-MM-dd  
  546.                     // HH:mm:ss").format(files[i].getTimestamp()));  
  547.                     dt = files[i].getTimestamp();  
  548.                     dt.add(Calendar.MONTH, com.ad.adweb.system.ClearExpiredDataDao.ExpiredDataMonthDiff);  
  549.                     // FTP服务器中保留最近多少个月的数据,默认为1个月  
  550.                     if (dt.compareTo(dtNow) <= 0)  
  551.                     {  
  552.                         isSuccessed = _ftp.deleteFile(FtpPathName + "/" + files[i].getName());  
  553.                           
  554.                         if (isSuccessed)  
  555.                         {  
  556.                             deleteNum++;  
  557.                             //System.out.println("deleteFile OK! -- " + files[i].getName() + " -- " + FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss").format(dt));  
  558.                         }  
  559.   
  560.                     }  
  561.                 }// for  
  562.             }  
  563.   
  564.         }  
  565.         catch (Exception ex)  
  566.         {  
  567.             throw new Exception(ex.getMessage());  
  568.         }  
  569.   
  570.         t2 = System.currentTimeMillis();  
  571.         System.out.println("FTP服务器过期数据文件清理 -- " + FtpPathName + " 目录," + deleteNum + " 个文件已删除,用时 " + (t2 - t1) + " ms!");  
  572.           
  573.         return deleteNum;  
  574.     }  
  575.   
  576.     /** 
  577.      * 获取FtpMode 
  578.      * @return String FtpMode 
  579.      */  
  580.     public String getFtpMode()  
  581.     {  
  582.         return FtpMode;  
  583.     }  
  584.   
  585.     /** 
  586.      * 设置FtpMode 
  587.      * @param ftpMode FtpMode 
  588.      */  
  589.     public void setFtpMode(String ftpMode)  
  590.     {  
  591.         FtpMode = ftpMode;  
  592.     }  
  593.   
  594. //  /**  
  595. //   * 获取ConfigClientFtpMode  
  596. //   * @return String ConfigClientFtpMode  
  597. //   */  
  598. //  public static String getConfigClientFtpMode()  
  599. //  {  
  600. //      return ConfigClientFtpMode;  
  601. //  }  
  602. //  
  603. //  /**  
  604. //   * 设置ConfigClientFtpMode  
  605. //   * @param configClientFtpMode ConfigClientFtpMode  
  606. //   */  
  607. //  public static void setConfigClientFtpMode(String configClientFtpMode)  
  608. //  {  
  609. //      ConfigClientFtpMode = configClientFtpMode;  
  610. //  }  
  611. //  
  612. //  /**  
  613. //   * 获取ConfigFtpMode  
  614. //   * @return String ConfigFtpMode  
  615. //   */  
  616. //  public static String getConfigFtpMode()  
  617. //  {  
  618. //      return ConfigFtpMode;  
  619. //  }  
  620. //  
  621. //  /**  
  622. //   * 设置ConfigFtpMode  
  623. //   * @param configFtpMode ConfigFtpMode  
  624. //   */  
  625. //  public static void setConfigFtpMode(String configFtpMode)  
  626. //  {  
  627. //      ConfigFtpMode = configFtpMode;  
  628. //  }  
  629.   
  630. }// END  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值