Apache Common-net Ftp客户端实例

来源:互联网 发布:大数据展示平台 编辑:程序博客网 时间:2024/06/05 04:17

原文链接:http://yangyangmyself.iteye.com/blog/1299997


 本人参考Apache Common-net 2.2 的Api以及官方网的测试代码而写的FTP客户端操作实例,此外引用了dom4j开源包用于将FTP服务器的目录结构保存成XML文件。需实现断点续传的功能,还请高手多多指教。 

Java代码  收藏代码
  1. package com.shine.Ftp.util;  
  2.   
  3. import java.io.BufferedOutputStream;  
  4. import java.io.File;  
  5. import java.io.FileInputStream;  
  6. import java.io.FileOutputStream;  
  7. import java.io.FileWriter;  
  8. import java.io.IOException;  
  9. import java.io.InputStream;  
  10. import java.util.Arrays;  
  11. import java.util.List;  
  12.   
  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.FTPListParseEngine;  
  17. import org.apache.commons.net.ftp.FTPReply;  
  18. import org.dom4j.Document;  
  19. import org.dom4j.DocumentHelper;  
  20. import org.dom4j.Element;  
  21. import org.dom4j.io.OutputFormat;  
  22. import org.dom4j.io.XMLWriter;  
  23.   
  24. public class FtpHelper {  
  25.   
  26.     private FTPClient ftp = null;  
  27.     /** 
  28.      * Ftp服务器 
  29.      */  
  30.     private String server;  
  31.     /** 
  32.      * 用户名 
  33.      */  
  34.     private String uname;  
  35.     /** 
  36.      * 密码 
  37.      */  
  38.     private String password;  
  39.     /** 
  40.      * 连接端口,默认21 
  41.      */  
  42.     private int port = 21;  
  43.       
  44.     private Document document ;  
  45.   
  46.     public FtpHelper(String server, int port, String uname,  
  47.             String password){  
  48.         this.server = server;  
  49.         if (this.port > 0){  
  50.             this.port = port;  
  51.         }  
  52.         this.uname = uname;  
  53.         this.password = password;  
  54.         //初始化  
  55.         ftp = new FTPClient();    
  56.     }  
  57.     /** 
  58.      * 连接FTP服务器 
  59.      *  
  60.      * @param server 
  61.      * @param uname 
  62.      * @param password 
  63.      * @return 
  64.      * @throws Exception 
  65.      */  
  66.     public FTPClient connectFTPServer() throws Exception {  
  67.         try {  
  68.             ftp.configure(getFTPClientConfig());  
  69.             ftp.connect(this.server, this.port);  
  70.             if (!ftp.login(this.uname, this.password)) {  
  71.                 ftp.logout();  
  72.                 ftp = null;  
  73.                 return ftp;  
  74.             }  
  75.   
  76.             // 文件类型,默认是ASCII  
  77.             ftp.setFileType(FTPClient.BINARY_FILE_TYPE);  
  78.             ftp.setControlEncoding("GBK");  
  79.             // 设置被动模式  
  80.             ftp.enterLocalPassiveMode();  
  81.             ftp.setConnectTimeout(2000);  
  82.             ftp.setBufferSize(1024);  
  83.             // 响应信息  
  84.             int replyCode = ftp.getReplyCode();  
  85.             if ((!FTPReply.isPositiveCompletion(replyCode))) {  
  86.                 // 关闭Ftp连接  
  87.                 closeFTPClient();  
  88.                 // 释放空间  
  89.                 ftp = null;  
  90.                 throw new Exception("登录FTP服务器失败,请检查![Server:" + server + "、"  
  91.                         + "User:" + uname + "、" + "Password:" + password);  
  92.             } else {  
  93.                 return ftp;  
  94.             }  
  95.         } catch (Exception e) {  
  96.             ftp.disconnect();  
  97.             ftp = null;  
  98.             throw e;  
  99.         }  
  100.     }  
  101.   
  102.     /** 
  103.      * 配置FTP连接参数 
  104.      *  
  105.      * @return 
  106.      * @throws Exception 
  107.      */  
  108.     public FTPClientConfig getFTPClientConfig() throws Exception {  
  109.         String systemKey = FTPClientConfig.SYST_NT;  
  110.         String serverLanguageCode = "zh";  
  111.         FTPClientConfig conf = new FTPClientConfig(systemKey);  
  112.         conf.setServerLanguageCode(serverLanguageCode);  
  113.         conf.setDefaultDateFormatStr("yyyy-MM-dd");  
  114.         return conf;  
  115.     }  
  116.   
  117.     /** 
  118.      * 向FTP根目录上传文件 
  119.      *  
  120.      * @param localFile 
  121.      * @param newName 
  122.      *            新文件名 
  123.      * @throws Exception 
  124.      */  
  125.     public Boolean uploadFile(String localFile, String newName)  
  126.             throws Exception {  
  127.         InputStream input = null;  
  128.         boolean success = false;  
  129.         try {  
  130.             File file = null;  
  131.             if (checkFileExist(localFile)) {  
  132.                 file = new File(localFile);  
  133.             }  
  134.             input = new FileInputStream(file);  
  135.             success = ftp.storeFile(newName, input);  
  136.             if (!success) {  
  137.                 throw new Exception("文件上传失败!");  
  138.             }  
  139.         } catch (Exception e) {  
  140.             throw e;  
  141.         } finally {  
  142.             if (input != null) {  
  143.                 input.close();  
  144.             }  
  145.         }  
  146.         return success;  
  147.     }  
  148.   
  149.     /** 
  150.      * 向FTP根目录上传文件 
  151.      *  
  152.      * @param input 
  153.      * @param newName 
  154.      *            新文件名 
  155.      * @throws Exception 
  156.      */  
  157.     public Boolean uploadFile(InputStream input, String newName)  
  158.             throws Exception {  
  159.         boolean success = false;  
  160.         try {  
  161.             success = ftp.storeFile(newName, input);  
  162.             if (!success) {  
  163.                 throw new Exception("文件上传失败!");  
  164.             }  
  165.         } catch (Exception e) {  
  166.             throw e;  
  167.         } finally {  
  168.             if (input != null) {  
  169.                 input.close();  
  170.             }  
  171.         }  
  172.         return success;  
  173.     }  
  174.   
  175.     /** 
  176.      * 向FTP指定路径上传文件 
  177.      *  
  178.      * @param localFile 
  179.      * @param newName 
  180.      *            新文件名 
  181.      * @param remoteFoldPath 
  182.      * @throws Exception 
  183.      */  
  184.     public Boolean uploadFile(String localFile, String newName,  
  185.             String remoteFoldPath) throws Exception {  
  186.   
  187.         InputStream input = null;  
  188.         boolean success = false;  
  189.         try {  
  190.             File file = null;  
  191.             if (checkFileExist(localFile)) {  
  192.                 file = new File(localFile);  
  193.             }  
  194.             input = new FileInputStream(file);  
  195.   
  196.             // 改变当前路径到指定路径  
  197.             if (!this.changeDirectory(remoteFoldPath)) {  
  198.                 System.out.println("服务器路径不存!");  
  199.                 return false;  
  200.             }  
  201.             success = ftp.storeFile(newName, input);  
  202.             if (!success) {  
  203.                 throw new Exception("文件上传失败!");  
  204.             }  
  205.         } catch (Exception e) {  
  206.             throw e;  
  207.         } finally {  
  208.             if (input != null) {  
  209.                 input.close();  
  210.             }  
  211.         }  
  212.         return success;  
  213.     }  
  214.   
  215.     /** 
  216.      * 向FTP指定路径上传文件 
  217.      *  
  218.      * @param input 
  219.      * @param newName 
  220.      *            新文件名 
  221.      * @param remoteFoldPath 
  222.      * @throws Exception 
  223.      */  
  224.     public Boolean uploadFile(InputStream input, String newName,  
  225.             String remoteFoldPath) throws Exception {  
  226.         boolean success = false;  
  227.         try {  
  228.             // 改变当前路径到指定路径  
  229.             if (!this.changeDirectory(remoteFoldPath)) {  
  230.                 System.out.println("服务器路径不存!");  
  231.                 return false;  
  232.             }  
  233.             success = ftp.storeFile(newName, input);  
  234.             if (!success) {  
  235.                 throw new Exception("文件上传失败!");  
  236.             }  
  237.         } catch (Exception e) {  
  238.             throw e;  
  239.         } finally {  
  240.             if (input != null) {  
  241.                 input.close();  
  242.             }  
  243.         }  
  244.         return success;  
  245.     }  
  246.   
  247.     /** 
  248.      * 从FTP服务器下载文件 
  249.      *  
  250.      * @param remotePath 
  251.      *            FTP路径(不包含文件名) 
  252.      * @param fileName 
  253.      *            下载文件名 
  254.      * @param localPath 
  255.      *            本地路径 
  256.      */  
  257.     public Boolean downloadFile(String remotePath, String fileName,  
  258.             String localPath) throws Exception {  
  259.   
  260.         BufferedOutputStream output = null;  
  261.         boolean success = false;  
  262.         try {  
  263.             // 检查本地路径  
  264.             this.checkFileExist(localPath);  
  265.             // 改变工作路径  
  266.             if (!this.changeDirectory(remotePath)) {  
  267.                 System.out.println("服务器路径不存在");  
  268.                 return false;  
  269.             }  
  270.             // 列出当前工作路径下的文件列表  
  271.             List<FTPFile> fileList = this.getFileList();  
  272.             if (fileList == null || fileList.size() == 0) {  
  273.                 System.out.println("服务器当前路径下不存在文件!");  
  274.                 return success;  
  275.             }  
  276.             for (FTPFile ftpfile : fileList) {  
  277.                 if (ftpfile.getName().equals(fileName)) {  
  278.                     File localFilePath = new File(localPath + File.separator  
  279.                             + ftpfile.getName());  
  280.                     output = new BufferedOutputStream(new FileOutputStream(  
  281.                             localFilePath));  
  282.                     success = ftp.retrieveFile(ftpfile.getName(), output);  
  283.                 }  
  284.             }  
  285.             if (!success) {  
  286.                 throw new Exception("文件下载失败!");  
  287.             }  
  288.         } catch (Exception e) {  
  289.             throw e;  
  290.         } finally {  
  291.             if (output != null) {  
  292.                 output.close();  
  293.             }  
  294.         }  
  295.         return success;  
  296.     }  
  297.   
  298.     /** 
  299.      * 从FTP服务器获取文件流 
  300.      *  
  301.      * @param remoteFilePath 
  302.      * @return 
  303.      * @throws Exception 
  304.      */  
  305.     public InputStream downloadFile(String remoteFilePath) throws Exception {  
  306.   
  307.         return ftp.retrieveFileStream(remoteFilePath);  
  308.     }  
  309.   
  310.     /** 
  311.      * 获取FTP服务器上指定路径下的文件列表 
  312.      *  
  313.      * @param filePath 
  314.      * @return 
  315.      */  
  316.     public List<FTPFile> getFtpServerFileList(String remotePath)  
  317.             throws Exception {  
  318.   
  319.         FTPListParseEngine engine = ftp.initiateListParsing(remotePath);  
  320.         List<FTPFile> ftpfiles = Arrays.asList(engine.getNext(25));  
  321.   
  322.         return ftpfiles;  
  323.     }  
  324.   
  325.     /** 
  326.      * 获取FTP服务器上[指定路径]下的文件列表 
  327.      *  
  328.      * @param path 
  329.      * @return 
  330.      * @throws Exception 
  331.      */  
  332.     public List<FTPFile> getFileList(String remotePath) throws Exception {  
  333.   
  334.         List<FTPFile> ftpfiles = Arrays.asList(ftp.listFiles(remotePath));  
  335.   
  336.         return ftpfiles;  
  337.     }  
  338.   
  339.     /** 
  340.      * 获取FTP服务器[当前工作路径]下的文件列表 
  341.      *  
  342.      * @param path 
  343.      * @return 
  344.      * @throws Exception 
  345.      */  
  346.     public List<FTPFile> getFileList() throws Exception {  
  347.   
  348.         List<FTPFile> ftpfiles = Arrays.asList(ftp.listFiles());  
  349.   
  350.         return ftpfiles;  
  351.     }  
  352.   
  353.     /** 
  354.      * 改变FTP服务器工作路径  
  355.      *  
  356.      * @param remoteFoldPath 
  357.      */  
  358.     public Boolean changeDirectory(String remoteFoldPath) throws Exception {  
  359.   
  360.         return ftp.changeWorkingDirectory(remoteFoldPath);  
  361.     }  
  362.   
  363.     /** 
  364.      * 删除文件 
  365.      *  
  366.      * @param remoteFilePath 
  367.      * @return 
  368.      * @throws Exception 
  369.      */  
  370.     public Boolean deleteFtpServerFile(String remoteFilePath) throws Exception {  
  371.   
  372.         return ftp.deleteFile(remoteFilePath);  
  373.     }  
  374.   
  375.     /** 
  376.      * 创建目录 
  377.      *  
  378.      * @param remoteFoldPath 
  379.      * @return 
  380.      */  
  381.     public boolean createFold(String remoteFoldPath) throws Exception {  
  382.   
  383.         boolean flag = ftp.makeDirectory(remoteFoldPath);  
  384.         if (!flag) {  
  385.             throw new Exception("创建目录失败");  
  386.         }  
  387.         return false;  
  388.     }  
  389.   
  390.     /** 
  391.      * 删除目录 
  392.      * @param remoteFoldPath 
  393.      * @return 
  394.      * @throws Exception 
  395.      */  
  396.     public boolean deleteFold(String remoteFoldPath) throws Exception {  
  397.           
  398.         return ftp.removeDirectory(remoteFoldPath) ;  
  399.     }  
  400.   
  401.     /** 
  402.      * 删除目录以及文件 
  403.      *  
  404.      * @param remoteFoldPath 
  405.      * @return 
  406.      */  
  407.     public boolean deleteFoldAndsubFiles(String remoteFoldPath)  
  408.             throws Exception {  
  409.   
  410.         boolean success = false;  
  411.         List<FTPFile> list = this.getFileList(remoteFoldPath);  
  412.         if (list == null || list.size() == 0) {  
  413.             return deleteFold(remoteFoldPath);  
  414.         }  
  415.         for (FTPFile ftpFile : list) {  
  416.               
  417.             String name = ftpFile.getName();  
  418.             if (ftpFile.isDirectory()) {  
  419.                 success = deleteFoldAndsubFiles(remoteFoldPath + "/" + name);  
  420.                 if (!success)  
  421.                     break;  
  422.             } else {  
  423.                 success = deleteFtpServerFile(remoteFoldPath + "/" + name);  
  424.                 if (!success)  
  425.                     break;  
  426.             }  
  427.         }  
  428.         if (!success)  
  429.             return false;  
  430.         success = deleteFold(remoteFoldPath);  
  431.         return success;  
  432.     }  
  433.   
  434.     /** 
  435.      * 检查本地路径是否存在 
  436.      *  
  437.      * @param filePath 
  438.      * @return 
  439.      * @throws Exception 
  440.      */  
  441.     public boolean checkFileExist(String filePath) throws Exception {  
  442.         boolean flag = false;  
  443.         File file = new File(filePath);  
  444.         if (!file.exists()) {  
  445.             throw new Exception("本地路径不存在,请检查!");  
  446.         } else {  
  447.             flag = true;  
  448.         }  
  449.         return flag;  
  450.     }  
  451.       
  452.     /** 
  453.      * 创建XML文件 
  454.      * @return 
  455.      */  
  456.     public Element getCurrentElement(){  
  457.         document = DocumentHelper.createDocument();  
  458.         return document.addElement("root");  
  459.     }  
  460.       
  461.     /** 
  462.      * 生成目录XML文件 
  463.      */  
  464.     public void createDirectoryXML(String remotePath,Element fatherElement) throws Exception{  
  465.   
  466.         List<FTPFile> list = this.getFileList();  
  467.         for(FTPFile ftpfile:list){  
  468.             Element currentElement = fatherElement; //当前的目录节点  
  469.             String newRemotePath = remotePath+ftpfile.getName();  
  470.             if(ftpfile.isDirectory()){  
  471.                 Element dirElement = fatherElement.addElement("dir") ;  
  472.                 dirElement.addAttribute("name",ftpfile.getName());  
  473.                 currentElement = dirElement;  
  474.                 this.changeDirectory(newRemotePath); //从根目录开始  
  475.                 createDirectoryXML(newRemotePath,dirElement);  
  476.             }else{  
  477.                  Element fileElement = fatherElement.addElement("file");//文件节点  
  478.                  fileElement.setText(ftpfile.getName()) ;  
  479.             }  
  480.         }  
  481.     }  
  482.       
  483.     /** 
  484.      * 保存xml 
  485.      */  
  486.     public void saveXML(){  
  487.         XMLWriter output = new XMLWriter();  
  488.         //输出格式化  
  489.         OutputFormat format = OutputFormat.createPrettyPrint();  
  490.         try {  
  491.             output = new XMLWriter(new FileWriter("src/com/shine/Ftp/config/dir.xml"), format);  
  492.             output.write(this.document);  
  493.             output.close();  
  494.         } catch (IOException e) {  
  495.             e.printStackTrace();  
  496.         }  
  497.     }  
  498.       
  499.     /** 
  500.      * 关闭FTP连接 
  501.      *  
  502.      * @param ftp 
  503.      * @throws Exception 
  504.      */  
  505.     public void closeFTPClient(FTPClient ftp) throws Exception {  
  506.   
  507.         try {  
  508.             if (ftp.isConnected())  
  509.                 ftp.logout();  
  510.                 ftp.disconnect();  
  511.         } catch (Exception e) {  
  512.             throw new Exception("关闭FTP服务出错!");  
  513.         }  
  514.     }  
  515.   
  516.     /** 
  517.      * 关闭FTP连接 
  518.      *  
  519.      * @throws Exception 
  520.      */  
  521.     public void closeFTPClient() throws Exception {  
  522.   
  523.         this.closeFTPClient(this.ftp);  
  524.     }  
  525.   
  526.     /** 
  527.      * Get Attribute Method 
  528.      *  
  529.      */  
  530.     public FTPClient getFtp() {  
  531.         return ftp;  
  532.     }  
  533.   
  534.     public String getServer() {  
  535.         return server;  
  536.     }  
  537.   
  538.     public String getUname() {  
  539.         return uname;  
  540.     }  
  541.   
  542.     public String getPassword() {  
  543.         return password;  
  544.     }  
  545.   
  546.     public int getPort() {  
  547.         return port;  
  548.     }  
  549.   
  550.     /** 
  551.      * Set Attribute Method 
  552.      *  
  553.      */  
  554.     public void setFtp(FTPClient ftp) {  
  555.         this.ftp = ftp;  
  556.     }  
  557.   
  558.     public void setServer(String server) {  
  559.         this.server = server;  
  560.     }  
  561.   
  562.     public void setUname(String uname) {  
  563.         this.uname = uname;  
  564.     }  
  565.   
  566.     public void setPassword(String password) {  
  567.         this.password = password;  
  568.     }  
  569.   
  570.     public void setPort(int port) {  
  571.         this.port = port;  
  572.     }  
  573.   
  574.     /** 
  575.      * 主方法(测试) 
  576.      *  
  577.      * 问题:上传时命名的新文件名不能有中文,否则上传失败. 
  578.      *  
  579.      * @param args 
  580.      */  
  581.     public static void main(String[] args) {  
  582.         try {  
  583.             FtpHelper fu = new FtpHelper("192.168.2.18"21"administrator","sunshine");  
  584.             fu.connectFTPServer();  
  585.             Element fatherElement = fu.getCurrentElement();  
  586.             fu.createDirectoryXML("/", fatherElement);  
  587.             fu.saveXML();  
  588.         } catch (Exception e) {  
  589.             System.out.println("异常信息:" + e.getMessage());  
  590.         }  
  591.     }  
  592. }  


  更新一下第469、474、474行的代码: 
Java代码  收藏代码
  1. String newRemotePath = (remotePath+"/"+ftpfile.getName()).replaceAll("//","/");  
  2. String currentWorkPath = this.printWorkingDirectory();  
  3. createDirectoryXML(currentWorkPath,dirElement);  


提供源码:(只需配置好一台Ftp服务器即可用)
  • FtpHelper.rar (3.3 KB)
  • 下载次数: 521
  • commons-net-2.2.jar (207.5 KB)
  • 下载次数: 398
  • dom4j-1.6.1.jar (306.5 KB)
  • 下载次数: 273

0 0