使用Apache Commons Net包中的FTPClient实现javaFTP来上传目录(新)

  1. package com.util;  
  2.   
  3. import java.io.*;  
  4. import java.net.SocketException;  
  5. import java.text.SimpleDateFormat;  
  6. import java.util.ArrayList;  
  7. import java.util.List;  
  8. import java.util.Properties;  
  9.   
  10. import org.apache.commons.logging.Log;  
  11. import org.apache.commons.logging.LogFactory;  
  12. import org.apache.commons.net.ftp.FTP;  
  13. import org.apache.commons.net.ftp.FTPClient;  
  14. import org.apache.commons.net.ftp.FTPClientConfig;  
  15. import org.apache.commons.net.ftp.FTPFile;  
  16. import org.apache.commons.net.ftp.FTPReply;  
  17.   
  18. public class FTPClientTest {  
  19.       
  20.     private static final Log logger = LogFactory.getLog(FTPClientTest.class);   
  21.   
  22.     private String userName;         //FTP 登录用户名   
  23.     private String password;         //FTP 登录密码   
  24.     private String ip;                     //FTP 服务器地址IP地址   
  25.     private int port;                        //FTP 端口   
  26.     private Properties property = null;    //属性集   
  27.     private String configFile = "conf/application.properties";    //配置文件的路径名   
  28.     private FTPClient ftpClient = null//FTP 客户端代理   
  29.     //时间格式化   
  30.     private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm");   
  31.     //FTP状态码   
  32.     public int i = 1;   
  33.   
  34.     /**  
  35.      * 连接到服务器  
  36.      *  
  37.      * @return true 连接服务器成功,false 连接服务器失败  
  38.      */   
  39.     public boolean connectServer() {   
  40.         boolean flag = true;   
  41.         if (ftpClient == null) {   
  42.             int reply;   
  43.             try {   
  44.                 if(setArg(configFile)){  
  45.                     ftpClient = new FTPClient();   
  46.                     ftpClient.setControlEncoding("GBK");   
  47.                     //ftpClient.configure(getFtpConfig());   
  48.                     ftpClient.connect(ip,port);   
  49.                     ftpClient.login(userName, password);  
  50.                     reply = ftpClient.getReplyCode();   
  51.                     ftpClient.setDataTimeout(120000);   
  52.   
  53.                     if (!FTPReply.isPositiveCompletion(reply)) {   
  54.                         ftpClient.disconnect();   
  55.                         logger.debug("FTP 服务拒绝连接!");   
  56.                         flag = false;   
  57.                     }   
  58.                     i++;   
  59.                 }else{  
  60.                     flag = false;   
  61.                 }  
  62.             } catch (SocketException e) {   
  63.                 flag = false;   
  64.                 e.printStackTrace();   
  65.                 logger.debug("登录ftp服务器 " + ip + " 失败,连接超时!");   
  66.             } catch (IOException e) {   
  67.                 flag = false;   
  68.                 e.printStackTrace();   
  69.                 logger.debug("登录ftp服务器 " + ip + " 失败,FTP服务器无法打开!");   
  70.             }   
  71.         }   
  72.         return flag;   
  73.     }  
  74.       
  75.     /** 
  76.      * 上传文件 
  77.      *  
  78.      * @param remoteFile 
  79.      *            远程文件路径,支持多级目录嵌套 
  80.      * @param localFile 
  81.      *            本地文件名称,绝对路径 
  82.      *  
  83.      */  
  84.     public boolean uploadFile(String remoteFile, File localFile)  
  85.             throws IOException {  
  86.         boolean flag = false;  
  87.         InputStream in = new FileInputStream(localFile);  
  88.         String remote = new String(remoteFile.getBytes("GBK"),"iso-8859-1");  
  89.         if(ftpClient.storeFile(remote, in)){  
  90.             flag = true;  
  91.             logger.debug(localFile.getAbsolutePath()+"上传文件成功!");  
  92.         }else{  
  93.             logger.debug(localFile.getAbsolutePath()+"上传文件失败!");  
  94.         }  
  95.         in.close();  
  96.         return flag;  
  97.     }  
  98.       
  99.     /**  
  100.      * 上传单个文件,并重命名  
  101.      *  
  102.      * @param localFile--本地文件路径  
  103.      * @param localRootFile--本地文件父文件夹路径  
  104.      * @param distFolder--新的文件名,可以命名为空""  
  105.      * @return true 上传成功,false 上传失败  
  106.      * @throws IOException  
  107.      */   
  108.     public boolean uploadFile(String local, String remote) throws IOException {   
  109.         boolean flag = true;   
  110.         String remoteFileName = remote;  
  111.         if (remote.contains("/")) {  
  112.             remoteFileName = remote.substring(remote.lastIndexOf("/") + 1);  
  113.             // 创建服务器远程目录结构,创建失败直接返回  
  114.             if (!CreateDirecroty(remote)) {  
  115.                 return false;  
  116.             }  
  117.         }  
  118.         FTPFile[] files = ftpClient.listFiles(new String(remoteFileName));  
  119.         File f = new File(local);  
  120.         if(!uploadFile(remoteFileName, f)){  
  121.             flag = false;  
  122.         }  
  123.         return flag;   
  124.     }   
  125.   
  126.     /**  
  127.      * 上传文件夹内的所有文件  
  128.      *  
  129.      *  
  130.      * @param filename 
  131.      *       本地文件夹绝对路径 
  132.      * @param uploadpath 
  133.      *       上传到FTP的路径,形式为/或/dir1/dir2/../ 
  134.      * @return true 上传成功,false 上传失败  
  135.      * @throws IOException 
  136.      */   
  137.     public List uploadManyFile(String filename, String uploadpath) {   
  138.             boolean flag = true;   
  139.             List l = new ArrayList();  
  140.             StringBuffer strBuf = new StringBuffer();   
  141.             int n = 0//上传失败的文件个数  
  142.             int m = 0//上传成功的文件个数  
  143.             try {     
  144.                 ftpClient.setFileType(FTP.BINARY_FILE_TYPE);   
  145.                 ftpClient.enterLocalPassiveMode();   
  146.                 ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);  
  147.                 ftpClient.changeWorkingDirectory("/");   
  148.                 File file = new File(filename);  
  149.                 File fileList[] = file.listFiles();   
  150.                 for (File upfile : fileList) {   
  151.                         if (upfile.isDirectory()) {  
  152.                           uploadManyFile(upfile.getAbsoluteFile().toString(),uploadpath);   
  153.                         } else {   
  154.                             String local = upfile.getCanonicalPath().replaceAll("\\\\","/");  
  155.                             String remote = uploadpath.replaceAll("\\\\","/") + local.substring(local.indexOf("/") + 1);  
  156.                             flag = uploadFile(local, remote);  
  157.                             ftpClient.changeWorkingDirectory("/");  
  158.                         }   
  159.                         if (!flag) {   
  160.                                 n++;  
  161.                                 strBuf.append(upfile.getName() + ",");   
  162.                                 logger.debug("文件[" + upfile.getName() + "]上传失败");  
  163.                         } else{  
  164.                             m++;  
  165.                         }  
  166.                 }   
  167.                 l.add(0, n);  
  168.                 l.add(1, m);  
  169.                 l.add(2, strBuf.toString());  
  170.             } catch (NullPointerException e) {   
  171.                 e.printStackTrace();   
  172.                 logger.debug("本地文件上传失败!找不到上传文件!", e);   
  173.             } catch (Exception e) {   
  174.                 e.printStackTrace();   
  175.                 logger.debug("本地文件上传失败!", e);   
  176.             }   
  177.             return l;  
  178.     }   
  179.   
  180.     /**  
  181.      * 下载文件  
  182.      *  
  183.      * @param remoteFileName             --服务器上的文件名  
  184.      * @param localFileName--本地文件名  
  185.      * @return true 下载成功,false 下载失败  
  186.      */   
  187.     public boolean loadFile(String remoteFileName, String localFileName) {   
  188.         boolean flag = true;   
  189.         // 下载文件   
  190.         BufferedOutputStream buffOut = null;   
  191.         try {   
  192.             buffOut = new BufferedOutputStream(new FileOutputStream(localFileName));   
  193.             flag = ftpClient.retrieveFile(remoteFileName, buffOut);   
  194.         } catch (Exception e) {   
  195.             e.printStackTrace();   
  196.             logger.debug("本地文件下载失败!", e);   
  197.         } finally {   
  198.             try {   
  199.                 if (buffOut != null)   
  200.                     buffOut.close();   
  201.             } catch (Exception e) {   
  202.                 e.printStackTrace();   
  203.             }   
  204.         }   
  205.         return flag;   
  206.     }   
  207.   
  208.     /**  
  209.      * 删除一个文件  
  210.      */   
  211.     public boolean deleteFile(String filename) {   
  212.         boolean flag = true;   
  213.         try {   
  214.             flag = ftpClient.deleteFile(filename);   
  215.             if (flag) {   
  216.                 logger.debug("删除文件"+filename+"成功!");  
  217.             } else {   
  218.                 logger.debug("删除文件"+filename+"成功!");  
  219.             }   
  220.         } catch (IOException ioe) {   
  221.             ioe.printStackTrace();   
  222.         }   
  223.         return flag;   
  224.     }   
  225.   
  226.     /**  
  227.      * 删除目录  
  228.      */   
  229.     public void deleteDirectory(String pathname) {   
  230.         try {   
  231.             File file = new File(pathname);   
  232.             if (file.isDirectory()) {   
  233.                 File file2[] = file.listFiles();   
  234.             } else {   
  235.                 deleteFile(pathname);   
  236.             }   
  237.             ftpClient.removeDirectory(pathname);   
  238.         } catch (IOException ioe) {   
  239.             ioe.printStackTrace();   
  240.         }   
  241.     }   
  242.   
  243.     /**  
  244.      * 删除空目录  
  245.      */   
  246.     public void deleteEmptyDirectory(String pathname) {   
  247.         try {   
  248.             ftpClient.removeDirectory(pathname);   
  249.         } catch (IOException ioe) {   
  250.             ioe.printStackTrace();   
  251.         }   
  252.     }   
  253.   
  254.     /**  
  255.      * 列出服务器上文件和目录  
  256.      *  
  257.      * @param regStr --匹配的正则表达式  
  258.      */   
  259.     public void listRemoteFiles(String regStr) {   
  260.         try {   
  261.             String files[] = ftpClient.listNames(regStr);   
  262.             if (files == null || files.length == 0)   
  263.                 logger.debug("没有任何文件!");  
  264.             else {   
  265.                 for (int i = 0; i < files.length; i++) {   
  266.                     System.out.println(files[i]);   
  267.                 }   
  268.             }   
  269.         } catch (Exception e) {   
  270.             e.printStackTrace();   
  271.         }   
  272.     }   
  273.   
  274.     /**  
  275.      * 列出Ftp服务器上的所有文件和目录  
  276.      */   
  277.     public void listRemoteAllFiles() {   
  278.         try {   
  279.             String[] names = ftpClient.listNames();   
  280.             for (int i = 0; i < names.length; i++) {   
  281.                 System.out.println(names[i]);   
  282.             }   
  283.         } catch (Exception e) {   
  284.             e.printStackTrace();   
  285.         }   
  286.     }   
  287.   
  288.     /**  
  289.      * 关闭连接  
  290.      */   
  291.     public void closeConnect() {   
  292.         try {   
  293.             if (ftpClient != null) {   
  294.                 ftpClient.logout();   
  295.                 ftpClient.disconnect();   
  296.             }   
  297.         } catch (Exception e) {   
  298.             e.printStackTrace();   
  299.         }   
  300.     }   
  301.   
  302.   
  303.     /**  
  304.      * 设置传输文件的类型[文本文件或者二进制文件]  
  305.      *  
  306.      * @param fileType--BINARY_FILE_TYPE、ASCII_FILE_TYPE  
  307.      *  
  308.      */   
  309.     public void setFileType(int fileType) {   
  310.         try {   
  311.             ftpClient.setFileType(fileType);   
  312.         } catch (Exception e) {   
  313.             e.printStackTrace();   
  314.         }   
  315.     }   
  316.   
  317.   
  318.     /**  
  319.      * 设置参数  
  320.      *  
  321.      * @param configFile --参数的配置文件  
  322.      */   
  323.     private boolean setArg(String configFile) {   
  324.         boolean flag = true;  
  325.         property = new Properties();   
  326.         BufferedInputStream inBuff = null;   
  327.         try {   
  328.             inBuff = new BufferedInputStream(new FileInputStream(getClass().getResource("/").getPath() + configFile));   
  329.             property.load(inBuff);   
  330.             userName = property.getProperty("username");   
  331.             password = property.getProperty("password");   
  332.             ip = property.getProperty("ip");   
  333.             port = Integer.parseInt(property.getProperty("port"));   
  334.         } catch (FileNotFoundException e1) {   
  335.             flag = false;  
  336.             logger.debug("配置文件 " + configFile + " 不存在!");  
  337.         } catch (IOException e) {   
  338.             flag = false;  
  339.             logger.debug("配置文件 " + configFile + " 无法读取!");  
  340.         }   
  341.         return flag;  
  342.     }   
  343.   
  344.        
  345.   
  346.     /**  
  347.      * 进入到服务器的某个目录下  
  348.      *  
  349.      * @param directory  
  350.      */   
  351.     public boolean changeWorkingDirectory(String directory) {   
  352.         boolean flag = true;  
  353.         try {   
  354.             flag = ftpClient.changeWorkingDirectory(directory);   
  355.             if (flag) {   
  356.                 logger.debug("进入文件夹"+ directory + " 成功!");  
  357.   
  358.         } else {    
  359.             logger.debug("进入文件夹"+ directory + " 失败!");  
  360.         }   
  361.         } catch (IOException ioe) {   
  362.             ioe.printStackTrace();   
  363.         }   
  364.         return flag;  
  365.     }   
  366.   
  367.     /**  
  368.      * 返回到上一层目录  
  369.      */   
  370.     public void changeToParentDirectory() {   
  371.         try {   
  372.             ftpClient.changeToParentDirectory();   
  373.         } catch (IOException ioe) {   
  374.             ioe.printStackTrace();   
  375.         }   
  376.     }   
  377.   
  378.     /**  
  379.      * 重命名文件  
  380.      *  
  381.      * @param oldFileName --原文件名  
  382.      * @param newFileName --新文件名  
  383.      */   
  384.     public void renameFile(String oldFileName, String newFileName) {   
  385.         try {   
  386.             ftpClient.rename(oldFileName, newFileName);   
  387.         } catch (IOException ioe) {   
  388.             ioe.printStackTrace();   
  389.         }   
  390.     }   
  391.   
  392.     /**  
  393.      * 设置FTP客服端的配置--一般可以不设置  
  394.      *  
  395.      * @return ftpConfig  
  396.      */   
  397.     private FTPClientConfig getFtpConfig() {   
  398.         FTPClientConfig ftpConfig = new FTPClientConfig(FTPClientConfig.SYST_UNIX);   
  399.         ftpConfig.setServerLanguageCode(FTP.DEFAULT_CONTROL_ENCODING);   
  400.         return ftpConfig;   
  401.     }   
  402.   
  403.     /**  
  404.      * 转码[ISO-8859-1 -> GBK] 不同的平台需要不同的转码  
  405.      *  
  406.      * @param obj  
  407.      * @return ""  
  408.      */   
  409.     private String iso8859togbk(Object obj) {   
  410.         try {   
  411.             if (obj == null)   
  412.                 return "";   
  413.             else   
  414.                 return new String(obj.toString().getBytes("iso-8859-1"), "GBK");   
  415.         } catch (Exception e) {   
  416.                 return "";   
  417.         }   
  418.     }   
  419.   
  420.     /**  
  421.      * 在服务器上创建一个文件夹  
  422.      *  
  423.      * @param dir 文件夹名称,不能含有特殊字符,如 \ 、/ 、: 、* 、?、 "、 <、>...  
  424.      */   
  425.     public boolean makeDirectory(String dir) {   
  426.         boolean flag = true;   
  427.         try {   
  428.             flag = ftpClient.makeDirectory(dir);   
  429.             if (flag) {   
  430.                 logger.debug("创建文件夹"+ dir + " 成功!");  
  431.   
  432.             } else {    
  433.                 logger.debug("创建文件夹"+ dir + " 失败!");  
  434.             }   
  435.         } catch (Exception e) {   
  436.             e.printStackTrace();   
  437.         }   
  438.         return flag;   
  439.     }  
  440.       
  441.     // 检查路径是否存在,存在返回true,否则false    
  442.     public boolean existFile(String path) throws IOException {      
  443.         boolean flag = false;      
  444.         FTPFile[] ftpFileArr = ftpClient.listFiles(path);      
  445.        /* for (FTPFile ftpFile : ftpFileArr) {     
  446.             if (ftpFile.isDirectory()     
  447.                     && ftpFile.getName().equalsIgnoreCase(path)) {     
  448.                 flag = true;     
  449.                 break;     
  450.             }     
  451.         } */  
  452.         if(ftpFileArr.length > 0){  
  453.             flag = true;      
  454.         }  
  455.         return flag;      
  456.     }    
  457.       
  458.     /** 
  459.      * 递归创建远程服务器目录 
  460.      *  
  461.      * @param remote 
  462.      *            远程服务器文件绝对路径 
  463.      *  
  464.      * @return 目录创建是否成功 
  465.      * @throws IOException 
  466.      */  
  467.      public boolean CreateDirecroty(String remote) throws IOException {  
  468.          boolean success = true;  
  469.          String directory = remote.substring(0, remote.lastIndexOf("/") + 1);  
  470.          // 如果远程目录不存在,则递归创建远程服务器目录  
  471.          if (!directory.equalsIgnoreCase("/")&& !changeWorkingDirectory(new String(directory))) {  
  472.             int start = 0;  
  473.              int end = 0;  
  474.              if (directory.startsWith("/")) {  
  475.                  start = 1;  
  476.              } else {  
  477.                  start = 0;  
  478.              }  
  479.              end = directory.indexOf("/", start);  
  480.              while (true) {  
  481.                  String subDirectory = new String(remote.substring(start, end).getBytes("GBK"),"iso-8859-1");  
  482.                  if (changeWorkingDirectory(subDirectory)) {  
  483.                      if (makeDirectory(subDirectory)) {  
  484.                          changeWorkingDirectory(subDirectory);  
  485.                      } else {  
  486.                         logger.debug("创建目录["+subDirectory+"]失败");  
  487.                         System.out.println("创建目录["+subDirectory+"]失败");  
  488.                          success = false;  
  489.                          return success;  
  490.                      }  
  491.                  }  
  492.                  start = end + 1;  
  493.                  end = directory.indexOf("/", start);  
  494.                  // 检查所有目录是否创建完毕  
  495.                  if (end <= start) {  
  496.                      break;  
  497.                  }  
  498.              }  
  499.          }  
  500.          return success;  
  501.     }  
  502.        
  503.     public static void main(String[] args) {  
  504.         FTPClientTest ftpClient = new FTPClientTest();  
  505.         if(ftpClient.connectServer()){  
  506.             ftpClient.setFileType(FTP.BINARY_FILE_TYPE);// 设置传输二进制文件   
  507.             ftpClient.uploadManyFile("H:\\d""/d/");   
  508.             ftpClient.closeConnect();// 关闭连接   
  509.         }  
  510.     }  
  511. }
  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值