分享

使用递归方法实现,向FTP服务器上传整个目录结构、从FTP服务器下载整个目录到本地的功能

 筱肆 2015-01-29

我最近由于在做一个关于FTP文件上传和下载的功能时候,发现Apache FTP jar包没有提供对整个目录结构的上传和下载功能,只能非目录类型的文件进行上传和下载操作,后来我查阅很多网上的实现方法,再结合自己的理解、以及符合自己的需求,完成了我自己的apache FTP jar包补充类。

上面是背景,基本叙述完毕,下面开始介绍实现方法和代码。


一。环境搭建:

1.使用的FileZilla Server开源免费软件,安装过后建立的本地FTP服务器。

2.使用的apache上下载FTP工具包,引用到工程目录中。

3.IDE,Eclipse,JDK6

二。介绍代码。

上传和下载目录的实现原理:对每一个层级的目录进行判断,是为目录类型、还是文件类型。

如果为目录类型,采用递归调用方法,检查到最底层的目录为止结束。

如果为文件类型,则调用上传或者下载方法对文件进行上传或者下载操作。

贴出代码:(其中有些没有代码,可以看看,还是很有用处的)



  1. package com.ftp;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileInputStream;  
  5. import java.io.FileOutputStream;  
  6. import java.io.IOException;  
  7. import java.io.InputStream;  
  8. import java.io.OutputStream;  
  9. import java.net.SocketException;  
  10.   
  11. import org.apache.commons.net.ftp.FTP;  
  12. import org.apache.commons.net.ftp.FTPClient;  
  13. import org.apache.commons.net.ftp.FTPClientConfig;  
  14. import org.apache.commons.net.ftp.FTPFile;  
  15. import org.apache.commons.net.ftp.FTPReply;  
  16.   
  17. public class RemoteFtpProcess extends FTPClient {  
  18.     private static FTPClient ftpClient = new FTPClient();  
  19.   
  20.     /** 
  21.      * 本方法用户登录远程的FTP服务器 
  22.      *  
  23.      * @param url :表示FTP的IP地址 
  24.      * @param port :FTP服务器端口,默认端口为21 
  25.      * @param userName :登录FTP的用户名 
  26.      * @param password :登录FTP的密码 
  27.      *  
  28.      * @return FTPClient:返回为FTPClient对象 
  29.      */  
  30.     public FTPClient loginFtp(String url, int port, String userName,  
  31.             String password) {  
  32.         try {  
  33.             ftpClient.connect(url, port);  
  34.             ftpClient.setControlEncoding("UTF-8");  
  35.             FTPClientConfig ftpConfig = new FTPClientConfig(FTPClientConfig.SYST_NT);  
  36.             ftpConfig.setServerLanguageCode("zh");  
  37.             ftpClient.login(userName, password);  
  38.             int reply = 0;  
  39.             reply = ftpClient.getReplyCode();  
  40.             System.out.println(reply);  
  41.             if (FTPReply.isPositiveCompletion(reply)) {  
  42.                 System.out.println("登录成功!");  
  43.             } else {  
  44.                 System.out.println("登录失败!");  
  45.             }  
  46.         } catch (SocketException e) {  
  47.             e.printStackTrace();  
  48.         } catch (IOException e) {  
  49.             e.printStackTrace();  
  50.         }  
  51.         return ftpClient;  
  52.     }  
  53.   
  54.     /** 
  55.      * @param ftpc :退出FTP登录 
  56.      * @return boolean :是否已经关闭连接 
  57.      *  
  58.      * @throws IOException 
  59.      */  
  60.     public static boolean closeConnections(FTPClient ftpc) throws IOException {  
  61.         boolean bool = false;  
  62.         ftpc.logout();  
  63.         return bool;  
  64.     }  
  65.   
  66.     /** 
  67.      * 方法用于上传文件到FTP服务器的指定文件夹中 
  68.      *  
  69.      * @param fileName :上传文件的名称 
  70.      * @param input :上传文件的输入流对象 
  71.      * @param toFtpPath :上传到FTP的目的路径 
  72.      *  
  73.      * @return boolean:表示上传是否成功 
  74.      *  
  75.      */  
  76.     public boolean uploadFileToFtp(String fileName, InputStream input,  
  77.             String toFtpPath) {  
  78.         boolean bool = false;  
  79.         try {  
  80.             // 使得能够处理中文编码  
  81.             fileName = new String(fileName.getBytes("GBK"), "ISO-8859-1");  
  82.             toFtpPath = new String(toFtpPath.getBytes("GBK"), "ISO-8859-1");  
  83.             // 转到上传文件的FTP目录中  
  84.             ftpClient.changeWorkingDirectory(toFtpPath);  
  85.             // 设置处理文件的类型为字节流的形式  
  86.             ftpClient.setFileType(FTP.BINARY_FILE_TYPE);  
  87.             // 如果缺省该句 传输txt正常 但图片和其他格式的文件传输出现乱码  
  88.             ftpClient.storeFile(fileName, input);  
  89.             input.close();  
  90.             bool = true;  
  91.         } catch (IOException e) {  
  92.             bool = false;  
  93.             e.printStackTrace();  
  94.         }   
  95.         return bool;  
  96.     }  
  97.   
  98.     /** 
  99.      * 方法用于从FTP服务器中下载文件 
  100.      *  
  101.      * @param ftpUrl :下载文件所处FTP中路径 
  102.      * @param fileName :下载的文件名称 
  103.      * @param outputSream :下载文件的输出流对象 
  104.      *  
  105.      * @return boolean :表示是否上传成功 
  106.      *  
  107.      */  
  108.     public boolean downloadFileFromFtp(String ftpUrl, String fileName,  
  109.             OutputStream outputStream) {  
  110.         boolean bool = false;  
  111.         try {  
  112.             ftpClient.changeWorkingDirectory(ftpUrl);  
  113.             FTPFile[] ftpFile = ftpClient.listFiles();  
  114.             for (int i = 0; i < ftpFile.length; i++) {  
  115.                 if (fileName.equals(ftpFile[i].getName())) {  
  116.                     ftpClient.retrieveFile(new String(ftpFile[i].getName()  
  117.                             .getBytes("GBK"), "ISO-8859-1"), outputStream);  
  118.                     outputStream.flush();  
  119.                     outputStream.close();  
  120.                 }  
  121.             }  
  122.             bool = true;  
  123.         } catch (IOException e) {  
  124.             e.printStackTrace();  
  125.             bool = false;  
  126.         }  
  127.         return bool;  
  128.     }  
  129.   
  130.     /** 
  131.      * 方法用户删除FTP上的指定的文件 
  132.      *  
  133.      * @param fileUrl :文件在FTP中的路径 
  134.      * @param fileName :文件的名称 
  135.      *  
  136.      * @return boolean:删除是否成功 
  137.      */  
  138.     public boolean deleteFileOnFtp(String fileUrl, String fileName) {  
  139.         boolean bool = false;  
  140.         try {  
  141.             ftpClient.changeWorkingDirectory(fileUrl);  
  142.             FTPFile[] ftpFiles = ftpClient.listFiles();  
  143.             System.out.println(ftpFiles.length);  
  144.             for (int i = 0; i < ftpFiles.length; i++) {  
  145.                 if (fileName.equals(ftpFiles[i].getName())) {  
  146.                     ftpClient.deleteFile(fileName);  
  147.                 }  
  148.             }  
  149.         } catch (IOException e) {  
  150.             e.printStackTrace();  
  151.         }  
  152.         return bool;  
  153.     }  
  154.   
  155.     /** 
  156.      * 判断指定文件中是否存在相同名称的文件 
  157.      *  
  158.      * @param remotePath :FTP上的远程目录 
  159.      * @param fileName:文件名称 
  160.      * @return boolean :判断是否存在相同名称 
  161.      *  
  162.      */  
  163.     public boolean isSameName(String remotePath, String fileName) {  
  164.         boolean bool = false;  
  165.         try {  
  166.             FTPFile[] ftpFiles = ftpClient.listFiles();  
  167.             System.out.println(ftpFiles.length);  
  168.             ftpClient.changeWorkingDirectory(remotePath);  
  169.             for (int i = 0; i < ftpFiles.length; i++) {  
  170.                 if (fileName.equals(ftpFiles[i].getName())) {  
  171.                     System.out.println("存在和指定文件相同名称的文件");  
  172.                     bool = true;  
  173.                 } else {  
  174.                     bool = false;  
  175.                 }  
  176.             }  
  177.         } catch (Exception e) {  
  178.             bool = false;  
  179.         }  
  180.         return bool;  
  181.     }  
  182.   
  183.     /** 
  184.      * 更改文件名称 
  185.      *  
  186.      */  
  187.     public String changeName(String remotePath, String fileName, String newName) {  
  188.         if (isSameName(remotePath, fileName)) {  
  189.             fileName = fileName + "." + newName;  
  190.         }  
  191.         return fileName;  
  192.     }  
  193.       
  194.       
  195.     public static void newFileOnFTP(String pathName){  
  196.         try {  
  197.             ftpClient.mkd(pathName);  
  198.         } catch (IOException e) {  
  199.             e.printStackTrace();  
  200.         }  
  201.     }  
  202.       
  203.     //上传整个目录到FTP的指定目录中  
  204.     public void uploadDirFiles(String dirPath,String toRemotePath) throws IOException{  
  205.         if (dirPath!=null && !dirPath.equals("")) {  
  206.             //建立上传目录的File对象  
  207.             File dirFile = new File(dirPath);  
  208.             //判断File对象是否为目录类型  
  209.             if (dirFile.isDirectory()) {  
  210.                 //如果是目录类型。  
  211.                 //在FTP上创建一个和File对象文件相同名称的文件夹  
  212.                 ftpClient.makeDirectory(toRemotePath+"//"+dirFile.getName());  
  213.                 //获得File对象中包含的子目录数组  
  214.                 File[] subFiles = dirFile.listFiles();  
  215.                 //路径  
  216.                 String path = toRemotePath+"//"+dirFile.getName();  
  217.                 System.out.println(path);  
  218.                 //判断数组是否为空  
  219.                 if (subFiles!=null && subFiles.length>0) {  
  220.                     //遍历整个File数组  
  221.                     for (int i = 0; i < subFiles.length; i++) {  
  222.                         //判断是否为目录类型  
  223.                         if (subFiles[i].isDirectory()) {  
  224.                             //如果为目录类型  
  225.                             //跳转到FTP的根目录层级  
  226.                             ftpClient.changeWorkingDirectory("//");  
  227.                             //在FTP上建立相同的目录名称  
  228.                             ftpClient.makeDirectory(path+"//"+subFiles[i].getName());  
  229.                             //递归调用自身方法,进行到下一层级的目录循环  
  230.                             uploadDirFiles(subFiles[i].getAbsolutePath(), path);  
  231.                         } else {  
  232.                             //如果为文件类型  
  233.                             //建立一个文件输出流对象  
  234.                             FileInputStream input = new FileInputStream(subFiles[i]);  
  235.                             //调用文件上传方法,将文件上传到FTP上  
  236.                             uploadFileToFtp(subFiles[i].getName(), input, path+"//");  
  237.                             //关闭文件输入流  
  238.                             input.close();  
  239.                         }  
  240.                     }  
  241.                 }  
  242.             } else {  
  243.                 //如果为文件类型  
  244.                 //建立一个文件输出流对象  
  245.                 FileInputStream input = new FileInputStream(dirFile);  
  246.                 //调用文件上传方法,将文件上传到FTP上  
  247.                 uploadFileToFtp(dirFile.getName(), input, toRemotePath);  
  248.                 //关闭文件输入流  
  249.                 input.close();  
  250.             }  
  251.         }  
  252.     }  
  253.       
  254.     //本方法用于下载FTP上的目录结构到本地中  
  255.     public void downloadDirFiles(String remotePath,String localPath,String fileName) throws IOException{  
  256.         if (remotePath!=null && !remotePath.equals("")) {  
  257.             //在本地建立一个相同的文件目录  
  258.             File localFile = new File(localPath+"\\"+fileName);  
  259.             localFile.mkdirs();  
  260.             //获得目录在本地的绝对路径  
  261.             localPath = localFile.getAbsolutePath();  
  262.             System.out.println(localPath);  
  263.             //获得FTPFile对象数组  
  264.             FTPFile[] ftpFiles = ftpClient.listFiles(new String(remotePath.getBytes("GBK"),"ISO-8859-1"));  
  265.             if (ftpFiles!=null && ftpFiles.length>0) {  
  266.                 for (int i = 0; i < ftpFiles.length; i++) {  
  267.                     FTPFile subFile = ftpFiles[i];  
  268.                     //判断是否为目录结构  
  269.                     if (subFile.isDirectory()) {  
  270.                         //如果为目录结构  
  271.                         //调用自身方法,进行下一层级目录循环  
  272.                         downloadDirFiles(remotePath+"//"+subFile.getName(), localPath, subFile.getName());  
  273.                     } else {  
  274.                         //如果不为目录结构,为文件类型  
  275.                         FileOutputStream outputStream = new FileOutputStream(new File(localPath+"\\"+subFile.getName()));  
  276.                         //调用下载方法对文件进行下载  
  277.                         downloadFileFromFtp(remotePath, subFile.getName(), outputStream);  
  278.                         //关闭文件输出流  
  279.                         outputStream.close();  
  280.                     }  
  281.                 }  
  282.             }  
  283.         }  
  284.     }  
  285. }  



编写一个测试main类,进行测试。

  1. package com.ftp;  
  2.   
  3. import java.io.IOException;  
  4.   
  5. import org.apache.commons.net.ftp.FTPClient;  
  6.   
  7. public class TestMain {  
  8.     public static void upload(){  
  9.         RemoteFtpProcess remote = new RemoteFtpProcess();  
  10.         FTPClient ftpClient = remote.loginFtp("127.0.0.1", 21, "root", "root");  
  11.         try {  
  12.             remote.uploadDirFiles("D:\\FTPTestA", "//");  
  13.         } catch (IOException e) {  
  14.             e.printStackTrace();  
  15.         }  
  16.     }  
  17.       
  18.     public static void download(){  
  19.         RemoteFtpProcess remote = new RemoteFtpProcess();  
  20.         FTPClient ftpClient = remote.loginFtp("127.0.0.1", 21, "root", "root");  
  21.         try {  
  22.             remote.downloadDirFiles("\\FTPTest", "E://", "FTPTestB  
  23. ");  
  24.         } catch (IOException e) {  
  25.             e.printStackTrace();  
  26.         }  
  27.     }  
  28.       
  29.     public static void main(String[] args) {  
  30.         download();  
  31.     }  
  32. }  


有什么更好地建议或者方法,请直接评论回答。

===============Over========================



    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多