分享

Apache FTP文件上传、下载、修改文件名、删除

 心不留意外尘 2016-07-17

 http://blog.csdn.net/boonya/article/details/24399901

2014

前言:Apache FTP 是应用比较广泛的FTP上传客户端工具,它易于操作,代码简略,结构清晰,是做FTP文件客户端管理软件的优先之选。FTP的操作包括:FTP文件上传(断点续传)、FTP文件下载、FTP文件重命名、FTP文件删除,这些操作已经将FTP应用管理的方式发挥的淋漓尽致了,So 我一直都用此种方式来实现FTP文件服务器的管理工作;下附FTP工具代码。

1、FTP文件操作状态枚举类

  1. package com.scengine.wtms.utils.ftp;  
  2.   
  3. public enum FTPStatus  
  4. {  
  5.     File_Exits(0), Create_Directory_Success(1), Create_Directory_Fail(2), Upload_From_Break_Success(3), Upload_From_Break_Faild(4), Download_From_Break_Success(5), Download_From_Break_Faild(6), Upload_New_File_Success(7), Upload_New_File_Failed(8), Delete_Remote_Success(9), Delete_Remote_Faild(10),Remote_Bigger_Local(11),Remote_smaller_local(12),Not_Exist_File(13),Remote_Rename_Success(14),Remote_Rename_Faild(15),File_Not_Unique(16);  
  6.   
  7.     private int status;  
  8.   
  9.     public int getStatus()  
  10.     {  
  11.         return status;  
  12.     }  
  13.   
  14.     public void setStatus(int status)  
  15.     {  
  16.         this.status = status;  
  17.     }  
  18.   
  19.     FTPStatus(int status)  
  20.     {  
  21.         this.status = status;  
  22.     }  
  23. }  

2、FTP文件操作工具代码

  1. package com.scengine.wtms.utils.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.io.PrintWriter;  
  10. import javax.servlet.http.HttpServletResponse;  
  11. import org.apache.commons.net.PrintCommandListener;  
  12. import org.apache.commons.net.ftp.FTP;  
  13. import org.apache.commons.net.ftp.FTPClient;  
  14. import org.apache.commons.net.ftp.FTPFile;  
  15. import org.apache.commons.net.ftp.FTPReply;  
  16. import com.scengine.wtms.utils.Log;  
  17.   
  18. public class FTPUtils  
  19. {  
  20.     private FTPClient ftpClient = new FTPClient();  
  21.   
  22.     /** 
  23.      * 对象构造 设置将过程中使用到的命令输出到控制台 
  24.      */  
  25.     public FTPUtils()  
  26.     {  
  27.         this.ftpClient.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));  
  28.     }  
  29.   
  30.     /** 
  31.      *  
  32.      * java编程中用于连接到FTP服务器 
  33.      *  
  34.      * @param hostname 
  35.      *            主机名 
  36.      *  
  37.      * @param port 
  38.      *            端口 
  39.      *  
  40.      * @param username 
  41.      *            用户名 
  42.      *  
  43.      * @param password 
  44.      *            密码 
  45.      *  
  46.      * @return 是否连接成功 
  47.      *  
  48.      * @throws IOException 
  49.      */  
  50.   
  51.     public boolean connect(String hostname, int port, String username, String password) throws IOException  
  52.     {  
  53.   
  54.         ftpClient.connect(hostname, port);  
  55.   
  56.         if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode()))  
  57.         {  
  58.   
  59.             if (ftpClient.login(username, password))  
  60.             {  
  61.                 return true;  
  62.             }  
  63.         }  
  64.         disconnect();  
  65.         return false;  
  66.   
  67.     }  
  68.   
  69.     /** 
  70.      * 删除远程FTP文件 
  71.      *  
  72.      * @param remote 
  73.      *            远程文件路径 
  74.      * @return 
  75.      * @throws IOException 
  76.      */  
  77.     public FTPStatus delete(String remote) throws IOException  
  78.     {  
  79.         ftpClient.enterLocalPassiveMode();  
  80.   
  81.         ftpClient.setFileType(FTP.BINARY_FILE_TYPE);  
  82.   
  83.         FTPStatus result = null;  
  84.   
  85.         FTPFile[] files = ftpClient.listFiles(remote);  
  86.         if (files.length == 1)  
  87.         {  
  88.             boolean status = ftpClient.deleteFile(remote);  
  89.             result = status ? FTPStatus.Delete_Remote_Success : FTPStatus.Delete_Remote_Faild;  
  90.         }  
  91.         else  
  92.         {  
  93.             result = FTPStatus.Not_Exist_File;  
  94.         }  
  95.         Log.getLogger(this.getClass()).info("FTP服务器文件删除标识:"+result);  
  96.         return result;  
  97.     }  
  98.       
  99.     /** 
  100.      * 重命名远程FTP文件 
  101.      *  
  102.      * @param name 
  103.      *            新远程文件名称(路径-必须保证在同一路径下) 
  104.      *             
  105.      * @param remote 
  106.      *            远程文件路径 
  107.      *             
  108.      * @return  是否成功 
  109.      *  
  110.      * @throws IOException 
  111.      */  
  112.     public FTPStatus rename(String name,String remote) throws IOException  
  113.     {  
  114.         ftpClient.enterLocalPassiveMode();  
  115.   
  116.         ftpClient.setFileType(FTP.BINARY_FILE_TYPE);  
  117.   
  118.         FTPStatus result = null;  
  119.   
  120.         FTPFile[] files = ftpClient.listFiles(remote);  
  121.         if (files.length == 1)  
  122.         {  
  123.             boolean status = ftpClient.rename(remote, name);  
  124.             result = status ? FTPStatus.Remote_Rename_Success : FTPStatus.Remote_Rename_Faild;  
  125.         }  
  126.         else  
  127.         {  
  128.             result = FTPStatus.Not_Exist_File;  
  129.         }  
  130.         Log.getLogger(this.getClass()).info("FTP服务器文件名更新标识:"+result);  
  131.         return result;  
  132.     }  
  133.       
  134.     /** 
  135.      *  
  136.      * 从FTP服务器上下载文件 
  137.      *  
  138.      * @param fileName 
  139.      *            下载文件的名字(包括后缀名) 
  140.      *  
  141.      * @param remote 
  142.      *            远程文件路径 
  143.      *  
  144.      * @param local 
  145.      *            本地文件路径 
  146.      *  
  147.      * @return 是否成功 
  148.      *  
  149.      * @throws IOException 
  150.      */  
  151.   
  152.     public FTPStatus download(String fileName,String remote,HttpServletResponse response) throws IOException  
  153.     {  
  154.         // 开启输出流弹出文件保存路径选择窗口  
  155.         response.setContentType("application/octet-stream");  
  156.           
  157.         response.setContentType("application/OCTET-STREAM;charset=UTF-8");  
  158.           
  159.         response.setHeader("Content-Disposition", "attachment;filename=" +fileName);  
  160.   
  161.         ftpClient.enterLocalPassiveMode();  
  162.   
  163.         ftpClient.setFileType(FTP.BINARY_FILE_TYPE);  
  164.           
  165.         FTPStatus result;  
  166.           
  167.         OutputStream out = response.getOutputStream();  
  168.           
  169.         boolean status = ftpClient.retrieveFile(remote, out);  
  170.           
  171.         result=status?FTPStatus.Download_From_Break_Success:FTPStatus.Download_From_Break_Faild;  
  172.           
  173.         Log.getLogger(this.getClass()).info("FTP服务器文件下载标识:"+result);  
  174.           
  175.         out.close();  
  176.           
  177.         return result;  
  178.     }  
  179.   
  180.     /** 
  181.      *  
  182.      * 从FTP服务器上下载文件 
  183.      *  
  184.      * @param remote 
  185.      *            远程文件路径 
  186.      *  
  187.      * @param local 
  188.      *            本地文件路径 
  189.      *  
  190.      * @return 是否成功 
  191.      *  
  192.      * @throws IOException 
  193.      */  
  194.   
  195.     @SuppressWarnings("resource")  
  196.     public FTPStatus download(String remote, String local) throws IOException  
  197.     {  
  198.   
  199.         ftpClient.enterLocalPassiveMode();  
  200.   
  201.         ftpClient.setFileType(FTP.BINARY_FILE_TYPE);  
  202.   
  203.         FTPStatus result;  
  204.   
  205.         File f = new File(local);  
  206.   
  207.         FTPFile[] files = ftpClient.listFiles(remote);  
  208.   
  209.         if (files.length != 1)  
  210.         {  
  211.             Log.getLogger(this.getClass()).info("远程文件不唯一");  
  212.             return FTPStatus.File_Not_Unique;  
  213.         }  
  214.   
  215.         long lRemoteSize = files[0].getSize();  
  216.   
  217.         if (f.exists())  
  218.         {  
  219.             OutputStream out = new FileOutputStream(f, true);  
  220.             Log.getLogger(this.getClass()).info("本地文件大小为:" + f.length());  
  221.   
  222.             if (f.length() >= lRemoteSize)  
  223.             {  
  224.   
  225.                 Log.getLogger(this.getClass()).info("本地文件大小大于远程文件大小,下载中止");  
  226.                 return FTPStatus.Remote_smaller_local;  
  227.   
  228.             }  
  229.   
  230.             ftpClient.setRestartOffset(f.length());  
  231.   
  232.             boolean status = ftpClient.retrieveFile(remote, out);  
  233.             result=status?FTPStatus.Download_From_Break_Success:FTPStatus.Download_From_Break_Faild;  
  234.             out.close();  
  235.   
  236.         } else  
  237.         {  
  238.             OutputStream out = new FileOutputStream(f);  
  239.             boolean status = ftpClient.retrieveFile(remote, out);  
  240.             result=status?FTPStatus.Download_From_Break_Success:FTPStatus.Download_From_Break_Faild;  
  241.             out.close();  
  242.         }  
  243.   
  244.         return result;  
  245.   
  246.     }  
  247.   
  248.     /** 
  249.      *  
  250.      * 上传文件到FTP服务器,支持断点续传 
  251.      *  
  252.      * @param local 
  253.      *            本地文件名称,绝对路径 
  254.      *  
  255.      * @param remote 
  256.      *            远程文件路径,使用/home/directory1/subdirectory/file.ext 
  257.      *            按照Linux上的路径指定方式,支持多级目录嵌套,支持递归创建不存在的目录结构 
  258.      *  
  259.      * @return 上传结果 
  260.      *  
  261.      * @throws IOException 
  262.      */  
  263.   
  264.     @SuppressWarnings("resource")  
  265.     public FTPStatus upload(String local, String remote) throws IOException  
  266.     {  
  267.         // 设置PassiveMode传输  
  268.         ftpClient.enterLocalPassiveMode();  
  269.   
  270.         // 设置以二进制流的方式传输  
  271.         ftpClient.setFileType(FTP.BINARY_FILE_TYPE);  
  272.   
  273.         FTPStatus result;  
  274.   
  275.         // 对远程目录的处理  
  276.         String remoteFileName = remote;  
  277.   
  278.         if (remote.contains("/"))  
  279.         {  
  280.   
  281.             remoteFileName = remote.substring(remote.lastIndexOf("/") + 1);  
  282.   
  283.             String directory = remote.substring(0, remote.lastIndexOf("/") + 1);  
  284.   
  285.             if (!directory.equalsIgnoreCase("/") && !ftpClient.changeWorkingDirectory(directory))  
  286.             {  
  287.   
  288.                 // 如果远程目录不存在,则递归创建远程服务器目录  
  289.   
  290.                 int start = 0;  
  291.   
  292.                 int end = 0;  
  293.   
  294.                 if (directory.startsWith("/"))  
  295.                 {  
  296.   
  297.                     start = 1;  
  298.   
  299.                 } else  
  300.                 {  
  301.   
  302.                     start = 0;  
  303.   
  304.                 }  
  305.   
  306.                 end = directory.indexOf("/", start);  
  307.   
  308.                 while (true)  
  309.                 {  
  310.   
  311.                     String subDirectory = remote.substring(start, end);  
  312.   
  313.                     if (!ftpClient.changeWorkingDirectory(subDirectory))  
  314.                     {  
  315.   
  316.                         if (ftpClient.makeDirectory(subDirectory))  
  317.                         {  
  318.   
  319.                             ftpClient.changeWorkingDirectory(subDirectory);  
  320.   
  321.                         } else  
  322.                         {  
  323.   
  324.                             Log.getLogger(this.getClass()).info("创建目录失败");  
  325.   
  326.                             return FTPStatus.Create_Directory_Fail;  
  327.   
  328.                         }  
  329.   
  330.                     }  
  331.   
  332.                     start = end + 1;  
  333.   
  334.                     end = directory.indexOf("/", start);  
  335.   
  336.                     // 检查所有目录是否创建完毕  
  337.   
  338.                     if (end <= start)  
  339.                     {  
  340.   
  341.                         break;  
  342.   
  343.                     }  
  344.   
  345.                 }  
  346.   
  347.             }  
  348.   
  349.         }  
  350.   
  351.         // 检查远程是否存在文件  
  352.   
  353.         FTPFile[] files = ftpClient.listFiles(remoteFileName);  
  354.   
  355.         if (files.length == 1)  
  356.         {  
  357.   
  358.             long remoteSize = files[0].getSize();  
  359.   
  360.             File f = new File(local);  
  361.   
  362.             long localSize = f.length();  
  363.   
  364.             if (remoteSize == localSize)  
  365.             {  
  366.   
  367.                 return FTPStatus.File_Exits;  
  368.   
  369.             } else if (remoteSize > localSize)  
  370.             {  
  371.   
  372.                 return FTPStatus.Remote_Bigger_Local;  
  373.   
  374.             }  
  375.   
  376.             // 尝试移动文件内读取指针,实现断点续传  
  377.   
  378.             InputStream is = new FileInputStream(f);  
  379.   
  380.             if (is.skip(remoteSize) == remoteSize)  
  381.             {  
  382.   
  383.                 ftpClient.setRestartOffset(remoteSize);  
  384.   
  385.                 if (ftpClient.storeFile(remote, is))  
  386.                 {  
  387.   
  388.                     return FTPStatus.Upload_From_Break_Success;  
  389.   
  390.                 }  
  391.   
  392.             }  
  393.   
  394.             // 如果断点续传没有成功,则删除服务器上文件,重新上传  
  395.   
  396.             if (!ftpClient.deleteFile(remoteFileName))  
  397.             {  
  398.   
  399.                 return FTPStatus.Delete_Remote_Faild;  
  400.   
  401.             }  
  402.   
  403.             is = new FileInputStream(f);  
  404.   
  405.             if (ftpClient.storeFile(remote, is))  
  406.             {  
  407.   
  408.                 result = FTPStatus.Upload_New_File_Success;  
  409.   
  410.             } else  
  411.             {  
  412.   
  413.                 result = FTPStatus.Upload_New_File_Failed;  
  414.   
  415.             }  
  416.   
  417.             is.close();  
  418.   
  419.         } else  
  420.         {  
  421.   
  422.             InputStream is = new FileInputStream(local);  
  423.   
  424.             if (ftpClient.storeFile(remoteFileName, is))  
  425.             {  
  426.   
  427.                 result = FTPStatus.Upload_New_File_Success;  
  428.   
  429.             } else  
  430.             {  
  431.   
  432.                 result = FTPStatus.Upload_New_File_Failed;  
  433.   
  434.             }  
  435.   
  436.             is.close();  
  437.         }  
  438.   
  439.         return result;  
  440.   
  441.     }  
  442.   
  443.     /** 
  444.      *  
  445.      * 断开与远程服务器的连接 
  446.      *  
  447.      * @throws IOException 
  448.      */  
  449.   
  450.     public void disconnect() throws IOException  
  451.     {  
  452.   
  453.         if (ftpClient.isConnected())  
  454.         {  
  455.             ftpClient.disconnect();  
  456.         }  
  457.   
  458.     }  
  459.   
  460.     public static void main(String[] args)  
  461.     {  
  462.         FTPUtils myFtp = new FTPUtils();  
  463.         try  
  464.         {  
  465.   
  466.             myFtp.connect("192.168.1.200", 21, "duser", "HTPDuserXP32");  
  467.   
  468.             Log.getLogger(FTPUtils.class).info(myFtp.upload("C:\\Users\\Administrator\\Desktop\\swing.drawer.jar", "/jars/swing.drawer.jar"));  
  469.   
  470.             myFtp.disconnect();  
  471.   
  472.         } catch (IOException e)  
  473.         {  
  474.   
  475.             Log.getLogger(FTPUtils.class).info("FTP上传文件异常:" + e.getMessage());  
  476.   
  477.         }  
  478.   
  479.     }  
  480.   
  481. }  


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

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多