java ftp

来源:互联网 发布:tpo模考软件下载 编辑:程序博客网 时间:2024/04/30 00:18

topMan'blog

  • 博客
  • 微博
  • 相册
  • 收藏
  • 留言
  • 关于我

Commons-net FTPClient上传下载的封装

    博客分类: 
  • 开源组件的应用
  • Apache开源组件研究
 

        在项目中使用到FTP功能,于是采用类似Spring的各种回调机制公用各种代码,减少代码的开发量,简化开发人员的学习难度.本文仅供学习交流使用,如有比较好的意见希望可以一起交流,再次表示感谢.

Java代码  收藏代码
  1. package easyway.tbs.transfer.ftp;  
  2.   
  3. import java.io.IOException;  
  4.   
  5. import org.apache.commons.net.ftp.FTPClient;  
  6. /** 
  7.  * FTPCLient回调 
  8.  * @author longgangabai 
  9.  * 
  10.  * @param <T> 
  11.  */  
  12. public interface FTPClientCallback<T> {  
  13.       
  14.     public T doTransfer(FTPClient ftp)throws IOException;  
  15.   
  16. }  

 

 

Java代码  收藏代码
  1. package easyway.tbs.transfer.ftp;  
  2.   
  3. import java.io.IOException;  
  4. import java.util.Collection;  
  5.   
  6. import org.apache.commons.net.ftp.FTPFile;  
  7.   
  8. /** 
  9.  * FTP操作的客户端操作上传下载 
  10.  * @author longgangbai 
  11.  * 
  12.  */  
  13. public interface FTPClientOperations {  
  14.     /** 
  15.      * 文件上传的方法 
  16.      * @param remote 
  17.      * @param local 
  18.      * @return 
  19.      * @throws IOException 
  20.      */  
  21.     public UploadStatus upload(String remote, String local) throws IOException;  
  22.       
  23.   
  24.      /** 
  25.       *  
  26.       * 从远程服务器目录下载文件到本地服务器目录中 
  27.       * @param localdir FTP服务器保存目录 
  28.       * @param remotedir FTP下载服务器目录 
  29.       * @param localTempFile临时下载记录文件 
  30.       * @return 成功返回true,否则返回false 
  31.       */  
  32.     public Collection<String> downloadList(final String localdir, final String remotedir,final String localTmpFile) throws IOException;  
  33.   
  34.     /** 
  35.      * 文件下载的方法 
  36.      * @param remote 
  37.      * @param local 
  38.      * @return 
  39.      * @throws IOException 
  40.      */  
  41.     public DownloadStatus downloadFile( String local,String remote) throws IOException;  
  42.       
  43.     /** 
  44.      * 查看服务器上文件列表方法 
  45.      * @param remotedir 
  46.      * @return 
  47.      * @throws IOException 
  48.      */  
  49.     public FTPFile[] list(final String remotedir) throws IOException;  
  50. }  

 

 

Java代码  收藏代码
  1. package easyway.tbs.transfer.ftp;  
  2.   
  3. import java.io.File;  
  4. import java.io.IOException;  
  5. import java.net.ConnectException;  
  6. import java.util.ArrayList;  
  7. import java.util.Collection;  
  8. import java.util.Properties;  
  9.   
  10. import org.apache.commons.collections.CollectionUtils;  
  11. import org.apache.commons.lang.ArrayUtils;  
  12. import org.apache.commons.lang.StringUtils;  
  13. import org.apache.commons.lang.math.NumberUtils;  
  14. import org.apache.commons.net.ftp.FTPClient;  
  15. import org.apache.commons.net.ftp.FTPClientConfig;  
  16. import org.apache.commons.net.ftp.FTPFile;  
  17. import org.apache.commons.net.ftp.FTPReply;  
  18. import org.apache.log4j.Logger;  
  19.   
  20. import easyway.tbs.commons.FileOperateUtils;  
  21. /** 
  22.  * Ftp回调模板 
  23.  *  
  24.  * @author longgangbai 
  25.  * 
  26.  */  
  27. public class FTPClientTemplate implements FTPClientOperations{  
  28.     private static final Logger logger = Logger.getLogger(FTPClientTemplate.class);  
  29.   
  30.     private static String DEAFULT_REMOTE_CHARSET="UTF-8";  
  31.     private static int DEAFULT_REMOTE_PORT=21;  
  32.     private static String separator = File.separator;  
  33.     private FTPClientConfig ftpClientConfig;  
  34.     private String host;  
  35.     private String username;  
  36.     private String password;  
  37.     private String port;  
  38.       
  39.     public FTPClientTemplate(String host,String user,String pwd,String port){  
  40.         this.host=host;  
  41.         this.username=user;  
  42.         this.password=pwd;  
  43.         this.port=port;  
  44.     }  
  45.     /** 
  46.      * 查看服务器上文件列表方法 
  47.      * @param remotedir 
  48.      * @return 
  49.      * @throws IOException 
  50.      */  
  51.     public FTPFile[] list(final String remotedir) throws IOException{  
  52.        return   execute(new FTPClientCallback<FTPFile[]>(){  
  53.         public FTPFile[] doTransfer(FTPClient ftp) throws IOException {  
  54.              ftp.changeWorkingDirectory(remotedir);  
  55.              FTPFile[] files= ftp.listFiles(remotedir);  
  56.             return files;  
  57.         }  
  58.         });  
  59.     }  
  60.     /** 
  61.      * 文件上传的方法 
  62.      * @param remote 
  63.      * @param local 
  64.      * @return 
  65.      * @throws IOException 
  66.      */  
  67.     public UploadStatus upload(final String local,final  String remote) throws IOException{  
  68.         return   execute(new FTPClientCallback<UploadStatus>(){  
  69.             public UploadStatus doTransfer(FTPClient ftpClient)throws IOException {  
  70.                 return FtpHelper.getInstance().upload(ftpClient, local, remote);  
  71.             }  
  72.         });  
  73.     }  
  74.       
  75.     /** 
  76.      * 上传文件到服务器,新上传和断点续传 
  77.      * @param remoteFile  远程文件名,在上传之前已经将服务器工作目录做了改变 
  78.      * @param localFile   本地文件File句柄,绝对路径 
  79.      * @param processStep  需要显示的处理进度步进值 
  80.      * @param ftpClient  FTPClient引用 
  81.      * @return 
  82.      * @throws IOException 
  83.      */  
  84.     public UploadStatus uploadFile(String remoteFile, File localFile,  
  85.     FTPClient ftpClient, long remoteSize) throws IOException {  
  86.          return FtpHelper.getInstance().uploadFile(remoteFile, localFile, ftpClient, remoteSize);  
  87.     }  
  88.   
  89.       
  90.      /** 
  91.       * 从远程服务器目录下载文件到本地服务器目录中 
  92.       * @param localdir FTP服务器保存目录 
  93.       * @param remotedir FTP下载服务器目录 
  94.       * @param localTempFile临时下载记录文件 
  95.       * @return  成功下载记录 
  96.       */  
  97.     public Collection<String> downloadList(final String localdir, final String remotedir,final String localTmpFile) throws IOException {  
  98.         return execute(new FTPClientCallback<Collection<String>>(){  
  99.             public Collection<String> doTransfer(final FTPClient ftp) throws IOException {  
  100.                 //切换到下载目录的中  
  101.                 ftp.changeWorkingDirectory(remotedir);  
  102.                 //获取目录中所有的文件信息  
  103.                 FTPFile[] ftpfiles=ftp.listFiles();  
  104.                 Collection<String> fileNamesCol=new ArrayList<String>();  
  105.                 //判断文件目录是否为空  
  106.                 if(!ArrayUtils.isEmpty(ftpfiles)){  
  107.                     for (FTPFile ftpfile : ftpfiles) {  
  108.                         String remoteFilePath=remotedir+separator+ftpfile.getName();  
  109.                         String localFilePath=localdir+separator+ftpfile.getName();  
  110.                         System.out.println("remoteFilePath ="+remoteFilePath +" localFilePath="+localFilePath);  
  111.                         //单个文件下载状态  
  112.                         DownloadStatus downStatus=downloadFile(remoteFilePath, localFilePath);  
  113.                         if(downStatus==DownloadStatus.Download_New_Success){  
  114.                             //临时目录中添加记录信息  
  115.                             fileNamesCol.add(remoteFilePath);  
  116.                         }  
  117.                     }  
  118.                 }  
  119.                 if(CollectionUtils.isNotEmpty(fileNamesCol)){  
  120.                     FileOperateUtils.writeLinesToFile(fileNamesCol, localTmpFile);  
  121.                 }  
  122.                 return  fileNamesCol;  
  123.             }  
  124.         });  
  125.     }  
  126.       
  127.     /** 
  128.      * 从FTP服务器上下载文件,支持断点续传,上传百分比汇报 
  129.      * @param remote  远程文件路径 
  130.      * @param local 本地文件路径 
  131.      * @return 上传的状态 
  132.      * @throws IOException 
  133.      *  
  134.      */  
  135.     public DownloadStatus downloadFile(final String remote, final String local) throws IOException{  
  136.         return   execute(new FTPClientCallback<DownloadStatus>(){  
  137.             public DownloadStatus doTransfer(FTPClient ftpClient) throws IOException {  
  138.                 DownloadStatus result=FtpHelper.getInstance().download(ftpClient, remote, local);  
  139.                 return result;  
  140.             }  
  141.         });  
  142.     }  
  143.     /** 
  144.      * 执行FTP回调操作的方法 
  145.      * @param callback   回调的函数 
  146.      * @throws IOException 
  147.      */  
  148.     public <T> T  execute(FTPClientCallback<T> callback) throws IOException{  
  149.         FTPClient ftp=new FTPClient();  
  150.         try {  
  151.                   
  152.             /*if(getFtpClientConfig()!=null){ 
  153.                  ftp.configure(getFtpClientConfig()); 
  154.                  ftpClientConfig.setServerTimeZoneId(TimeZone.getDefault().getID()); 
  155.             }*/  
  156.             //登录FTP服务器  
  157.             try {  
  158.                 //设置超时时间    
  159.                 ftp.setDataTimeout(7200);  
  160.                 //设置默认编码  
  161.                  ftp.setControlEncoding(DEAFULT_REMOTE_CHARSET);  
  162.                 //设置默认端口  
  163.                 ftp.setDefaultPort(DEAFULT_REMOTE_PORT);  
  164.                 //设置是否显示隐藏文件  
  165.                 ftp.setListHiddenFiles(false);  
  166.                 //连接ftp服务器  
  167.                 if(StringUtils.isNotEmpty(port)&&NumberUtils.isDigits(port)){  
  168.                         ftp.connect(host, Integer.valueOf(port));  
  169.                 }else{  
  170.                     ftp.connect(host);  
  171.                 }  
  172.             } catch(ConnectException e) {  
  173.                 logger.error("连接FTP服务器失败:"+ftp.getReplyString()+ftp.getReplyCode());  
  174.                 throw new IOException("Problem connecting the FTP-server fail",e);  
  175.             }  
  176.             //得到连接的返回编码  
  177.             int reply=ftp.getReplyCode();  
  178.               
  179.             if(!FTPReply.isPositiveCompletion(reply)){  
  180.                 ftp.disconnect();  
  181.             }  
  182.             //登录失败权限验证失败  
  183.             if(!ftp.login(getUsername(), getPassword())) {  
  184.                 ftp.quit();  
  185.                 ftp.disconnect();  
  186.                 logger.error("连接FTP服务器用户或者密码失败::"+ftp.getReplyString());  
  187.                 throw new IOException("Cant Authentificate to FTP-Server");  
  188.             }  
  189.             if(logger.isDebugEnabled()){  
  190.                 logger.info("成功登录FTP服务器:"+host+" 端口:"+port);  
  191.             }  
  192.             ftp.setFileType(FTPClient.BINARY_FILE_TYPE);  
  193.             //回调FTP的操作  
  194.             return callback.doTransfer(ftp);  
  195.         }finally{  
  196.             //FTP退出  
  197.             ftp.logout();  
  198.             //断开FTP连接  
  199.             if(ftp.isConnected()){  
  200.                 ftp.disconnect();  
  201.             }  
  202.         }  
  203.     }  
  204.       
  205.       protected String resolveFile(String file)  
  206.       {  
  207.           return null;  
  208.         //return file.replace(System.getProperty("file.separator").charAt(0), this.remoteFileSep.charAt(0));  
  209.       }  
  210.       
  211.     /** 
  212.      * 获取FTP的配置操作系统 
  213.      * @return 
  214.      */  
  215.     public FTPClientConfig getFtpClientConfig() {  
  216.          //获得系统属性集    
  217.         Properties props=System.getProperties();  
  218.         //操作系统名称  
  219.         String osname=props.getProperty("os.name");    
  220.         //针对window系统  
  221.         if(osname.equalsIgnoreCase("Windows XP")){  
  222.             ftpClientConfig=new FTPClientConfig(FTPClientConfig.SYST_NT);  
  223.         //针对linux系统  
  224.         }else if(osname.equalsIgnoreCase("Linux")){  
  225.             ftpClientConfig=new FTPClientConfig(FTPClientConfig.SYST_UNIX);  
  226.         }  
  227.         if(logger.isDebugEnabled()){  
  228.             logger.info("the ftp client system os Name "+osname);  
  229.         }  
  230.         return ftpClientConfig;  
  231.     }  
  232.       
  233.       
  234.   
  235.     public String getHost() {  
  236.         return host;  
  237.     }  
  238.   
  239.     public void setHost(String host) {  
  240.         this.host = host;  
  241.     }  
  242.   
  243.     public String getPassword() {  
  244.         return password;  
  245.     }  
  246.   
  247.     public void setPassword(String password) {  
  248.         this.password = password;  
  249.     }  
  250.   
  251.     public String getUsername() {  
  252.         return username;  
  253.     }  
  254.   
  255.     public void setUsername(String username) {  
  256.         this.username = username;  
  257.     }  
  258.   
  259.       
  260.       
  261.   
  262. }  

 

 

Java代码  收藏代码
  1. package easyway.tbs.transfer.ftp;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileOutputStream;  
  5. import java.io.IOException;  
  6. import java.io.InputStream;  
  7. import java.io.OutputStream;  
  8. import java.io.RandomAccessFile;  
  9. import java.util.StringTokenizer;  
  10.   
  11. import org.apache.commons.net.ftp.FTP;  
  12. import org.apache.commons.net.ftp.FTPClient;  
  13. import org.apache.commons.net.ftp.FTPFile;  
  14. import org.apache.commons.net.ftp.FTPReply;  
  15. /** 
  16.  * FTP下载工具类 
  17.  * @author longgangbai 
  18.  * 
  19.  */  
  20. public class FtpHelper {  
  21.     private static String DEAFULT_REMOTE_CHARSET="GBK";  
  22.     private static String DEAFULT_LOCAL_CHARSET="iso-8859-1";  
  23.   
  24.   
  25.       
  26.     private static FtpHelper instance=new FtpHelper();  
  27.       
  28.     public static FtpHelper getInstance(){  
  29.          return instance;  
  30.     }  
  31.     /** 
  32.      * 连接到FTP服务器 
  33.      * @param hostname主机名 
  34.      * @param port 端口 
  35.      * @param username 用户名 
  36.      * @param password 密码 
  37.      * @return 是否连接成功 
  38.      * @throws IOException 
  39.      */  
  40.     public  boolean connect(FTPClient ftpClient,String hostname, int port, String username,String password) throws IOException {  
  41.         ftpClient.connect(hostname, port);  
  42.         ftpClient.setControlEncoding(DEAFULT_REMOTE_CHARSET);  
  43.         if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {  
  44.             if (ftpClient.login(username, password)) {  
  45.                 return true;  
  46.             }  
  47.         }  
  48.         disconnect(ftpClient);  
  49.         return false;  
  50.     }  
  51.   
  52.     /** 
  53.      * 从FTP服务器上下载文件,支持断点续传,上传百分比汇报 
  54.      * @param remoteFilePath  远程文件路径 
  55.      * @param localFilePath 本地文件路径 
  56.      * @return 上传的状态 
  57.      * @throws IOException 
  58.      */  
  59.     public DownloadStatus download(FTPClient ftpClient,String remoteFilePath, String localFilePath)  
  60.     throws IOException {  
  61.         // 设置被动模式  
  62.         ftpClient.enterLocalPassiveMode();  
  63.         // 设置以二进制方式传输  
  64.         ftpClient.setFileType(FTP.BINARY_FILE_TYPE);  
  65.         DownloadStatus result;  
  66.         // 检查远程文件是否存在  
  67.         FTPFile[] files = ftpClient.listFiles(new String(  
  68.         remoteFilePath.getBytes(DEAFULT_REMOTE_CHARSET), DEAFULT_LOCAL_CHARSET));  
  69.         if (files.length != 1) {  
  70.             System.out.println("远程文件不存在");  
  71.             return DownloadStatus.Remote_File_Noexist;  
  72.         }  
  73.         long lRemoteSize = files[0].getSize();  
  74.         File f = new File(localFilePath);  
  75.         // 本地存在文件,进行断点下载  
  76.         if (f.exists()) {  
  77.             long localSize = f.length();  
  78.             // 判断本地文件大小是否大于远程文件大小  
  79.             if (localSize >= lRemoteSize) {  
  80.                 System.out.println("本地文件大于远程文件,下载中止");  
  81.                 return DownloadStatus.Local_Bigger_Remote;  
  82.             }  
  83.             // 进行断点续传,并记录状态  
  84.             FileOutputStream out = new FileOutputStream(f, true);  
  85.             ftpClient.setRestartOffset(localSize);  
  86.             InputStream in = ftpClient.retrieveFileStream(new String(remoteFilePath  
  87.             .getBytes(DEAFULT_REMOTE_CHARSET), DEAFULT_LOCAL_CHARSET));  
  88.             byte[] bytes = new byte[1024];  
  89.             long step = lRemoteSize / 100;  
  90.             long process = localSize / step;  
  91.             int c;  
  92.             while ((c = in.read(bytes)) != -1) {  
  93.                 out.write(bytes, 0, c);  
  94.                 localSize += c;  
  95.                 long nowProcess = localSize / step;  
  96.                 if (nowProcess > process) {  
  97.                     process = nowProcess;  
  98.                     if (process % 10 == 0){  
  99.                         System.out.println("下载进度:" + process);  
  100.                     }  
  101.                     // TODO 更新文件下载进度,值存放在process变量中  
  102.                 }  
  103.             }  
  104.             in.close();  
  105.             out.close();  
  106.             boolean isDo = ftpClient.completePendingCommand();  
  107.             if (isDo) {  
  108.                 result = DownloadStatus.Download_From_Break_Success;  
  109.             } else {  
  110.                 result = DownloadStatus.Download_From_Break_Failed;  
  111.             }  
  112.         } else {  
  113.             OutputStream out = new FileOutputStream(f);  
  114.             InputStream in = ftpClient.retrieveFileStream(new String(remoteFilePath  
  115.             .getBytes(DEAFULT_REMOTE_CHARSET), DEAFULT_LOCAL_CHARSET));  
  116.             byte[] bytes = new byte[1024];  
  117.             long step = lRemoteSize / 100;  
  118.             long process = 0;  
  119.             long localSize = 0L;  
  120.             int c;  
  121.             while ((c = in.read(bytes)) != -1) {  
  122.                 out.write(bytes, 0, c);  
  123.                 localSize += c;  
  124.                 long nowProcess = localSize / step;  
  125.                 if (nowProcess > process) {  
  126.                     process = nowProcess;  
  127.                     if (process % 10 == 0){  
  128.                         System.out.println("下载进度:" + process);  
  129.                     }  
  130.                     // TODO 更新文件下载进度,值存放在process变量中  
  131.                 }  
  132.             }  
  133.             in.close();  
  134.             out.close();  
  135.             boolean upNewStatus = ftpClient.completePendingCommand();  
  136.             if (upNewStatus) {  
  137.                 result = DownloadStatus.Download_New_Success;  
  138.             } else {  
  139.                 result = DownloadStatus.Download_New_Failed;  
  140.             }  
  141.         }  
  142.         return result;  
  143.     }  
  144.     /** 
  145.      *  
  146.      * 上传文件到FTP服务器,支持断点续传 
  147.      * @param localFilePath  本地文件名称,绝对路径 
  148.      * @param remoteFilePath   远程文件路径,使用/home/directory1/subdirectory/file.ext 
  149.      * 按照Linux上的路径指定方式,支持多级目录嵌套,支持递归创建不存在的目录结构 
  150.      * @return 上传结果 
  151.      * @throws IOException 
  152.      */  
  153.     public UploadStatus upload(FTPClient ftpClient,String localFilePath, String remoteFilePath) throws IOException {  
  154.         // 设置PassiveMode传输  
  155.         ftpClient.enterLocalPassiveMode();  
  156.         // 设置以二进制流的方式传输  
  157.         ftpClient.setFileType(FTP.BINARY_FILE_TYPE);  
  158.         ftpClient.setControlEncoding(DEAFULT_REMOTE_CHARSET);  
  159.         UploadStatus result;  
  160.         // 对远程目录的处理  
  161.         String remoteFileName = remoteFilePath;  
  162.         if (remoteFilePath.contains("/")) {  
  163.             remoteFileName = remoteFilePath.substring(remoteFilePath.lastIndexOf("/") + 1);  
  164.             // 创建服务器远程目录结构,创建失败直接返回  
  165.             if (createDirecroty(remoteFilePath, ftpClient) == UploadStatus.Create_Directory_Fail) {  
  166.                 return UploadStatus.Create_Directory_Fail;  
  167.             }  
  168.         }  
  169.         // ftpClient.feat();  
  170.         // System.out.println( ftpClient.getReply());  
  171.         // System.out.println( ftpClient.acct(null));  
  172.         // System.out.println(ftpClient.getReplyCode());  
  173.         // System.out.println(ftpClient.getReplyString());  
  174.         // 检查远程是否存在文件  
  175.         FTPFile[] files = ftpClient.listFiles(new String(remoteFileName  
  176.         .getBytes(DEAFULT_REMOTE_CHARSET), DEAFULT_LOCAL_CHARSET));  
  177.         if (files.length == 1) {  
  178.             long remoteSize = files[0].getSize();  
  179.             File f = new File(localFilePath);  
  180.             long localSize = f.length();  
  181.             if (remoteSize == localSize) { // 文件存在  
  182.                 return UploadStatus.File_Exits;  
  183.             } else if (remoteSize > localSize) {  
  184.                 return UploadStatus.Remote_Bigger_Local;  
  185.             }  
  186.             // 尝试移动文件内读取指针,实现断点续传  
  187.             result = uploadFile(remoteFileName, f, ftpClient, remoteSize);  
  188.             // 如果断点续传没有成功,则删除服务器上文件,重新上传  
  189.             if (result == UploadStatus.Upload_From_Break_Failed) {  
  190.                 if (!ftpClient.deleteFile(remoteFileName)) {  
  191.                     return UploadStatus.Delete_Remote_Faild;  
  192.                 }  
  193.                 result = uploadFile(remoteFileName, f, ftpClient, 0);  
  194.             }  
  195.         } else {  
  196.             result = uploadFile(remoteFileName, new File(localFilePath), ftpClient, 0);  
  197.         }  
  198.         return result;  
  199.     }  
  200.     /** 
  201.      *  
  202.      * 断开与远程服务器的连接 
  203.      * @throws IOException 
  204.      */  
  205.     public void disconnect(FTPClient ftpClient) throws IOException {  
  206.         if (ftpClient.isConnected()) {  
  207.             ftpClient.disconnect();  
  208.         }  
  209.     }  
  210.     /** 
  211.      * 递归创建远程服务器目录 
  212.      * @param remote 远程服务器文件绝对路径 
  213.      * @param ftpClient  FTPClient对象 
  214.      * @return 目录创建是否成功 
  215.      * @throws IOException 
  216.      */  
  217.     public UploadStatus createDirecroty(String remote, FTPClient ftpClient)  
  218.     throws IOException {  
  219.         UploadStatus status = UploadStatus.Create_Directory_Success;  
  220.         String directory = remote.substring(0, remote.lastIndexOf("/") + 1);  
  221.         if (!directory.equalsIgnoreCase("/")  
  222.         && !ftpClient.changeWorkingDirectory(new String(directory  
  223.         .getBytes(DEAFULT_REMOTE_CHARSET), DEAFULT_LOCAL_CHARSET))) {  
  224.             // 如果远程目录不存在,则递归创建远程服务器目录  
  225.             int start = 0;  
  226.             int end = 0;  
  227.             if (directory.startsWith("/")) {  
  228.                 start = 1;  
  229.             } else {  
  230.                 start = 0;  
  231.             }  
  232.             end = directory.indexOf("/", start);  
  233.             while (true) {  
  234.                 String subDirectory = new String(remote.substring(start, end)  
  235.                 .getBytes(DEAFULT_REMOTE_CHARSET), DEAFULT_LOCAL_CHARSET);  
  236.                 if (!ftpClient.changeWorkingDirectory(subDirectory)) {  
  237.                     if (ftpClient.makeDirectory(subDirectory)) {  
  238.                         ftpClient.changeWorkingDirectory(subDirectory);  
  239.                     } else {  
  240.                         System.out.println("创建目录失败");  
  241.                         return UploadStatus.Create_Directory_Fail;  
  242.                     }  
  243.                 }  
  244.                 start = end + 1;  
  245.                 end = directory.indexOf("/", start);  
  246.                 // 检查所有目录是否创建完毕  
  247.                 if (end <= start) {  
  248.                     break;  
  249.                 }  
  250.             }  
  251.         }  
  252.         return status;  
  253.     }  
  254.   
  255.     /** 
  256.      * 上传文件到服务器,新上传和断点续传 
  257.      * @param remoteFile  远程文件名,在上传之前已经将服务器工作目录做了改变 
  258.      * @param localFile   本地文件File句柄,绝对路径 
  259.      * @param processStep  需要显示的处理进度步进值 
  260.      * @param ftpClient  FTPClient引用 
  261.      * @return 
  262.      * @throws IOException 
  263.      */  
  264.     public UploadStatus uploadFile(String remoteFile, File localFile,  
  265.     FTPClient ftpClient, long remoteSize) throws IOException {  
  266.         UploadStatus status;  
  267.         // 显示进度的上传  
  268.         long step = localFile.length() / 100;  
  269.         long process = 0;  
  270.         long localreadbytes = 0L;  
  271.         RandomAccessFile raf = new RandomAccessFile(localFile, "r");  
  272.         String remote = new String(remoteFile.getBytes(DEAFULT_REMOTE_CHARSET), DEAFULT_LOCAL_CHARSET);  
  273.         OutputStream out = ftpClient.appendFileStream(remote);  
  274.         if (out == null)  
  275.         {  
  276.             String message = ftpClient.getReplyString();  
  277.             throw new RuntimeException(message);  
  278.         }  
  279.         // 断点续传  
  280.         if (remoteSize > 0) {  
  281.             ftpClient.setRestartOffset(remoteSize);  
  282.             process = remoteSize / step;  
  283.             raf.seek(remoteSize);  
  284.             localreadbytes = remoteSize;  
  285.         }  
  286.         byte[] bytes = new byte[1024];  
  287.         int c;  
  288.         while ((c = raf.read(bytes)) != -1) {  
  289.             out.write(bytes, 0, c);  
  290.             localreadbytes += c;  
  291.             if (localreadbytes / step != process) {  
  292.                 process = localreadbytes / step;  
  293.                 System.out.println("上传进度:" + process);  
  294.                 // TODO 汇报上传状态  
  295.             }  
  296.         }  
  297.         out.flush();  
  298.         raf.close();  
  299.         out.close();  
  300.         boolean result = ftpClient.completePendingCommand();  
  301.         if (remoteSize > 0) {  
  302.             status = result ? UploadStatus.Upload_From_Break_Success  
  303.             : UploadStatus.Upload_From_Break_Failed;  
  304.         } else {  
  305.             status = result ? UploadStatus.Upload_New_File_Success  
  306.             : UploadStatus.Upload_New_File_Failed;  
  307.         }  
  308.         return status;  
  309.     }  
  310.       
  311.       
  312.      protected void makeRemoteDir(FTPClient ftp, String dir)  
  313.         throws IOException  
  314.       {  
  315.         String workingDirectory = ftp.printWorkingDirectory();  
  316.         if (dir.indexOf("/") == 0) {  
  317.           ftp.changeWorkingDirectory("/");  
  318.         }  
  319.         String subdir = new String();  
  320.         StringTokenizer st = new StringTokenizer(dir, "/");  
  321.         while (st.hasMoreTokens()) {  
  322.           subdir = st.nextToken();  
  323.           if (!(ftp.changeWorkingDirectory(subdir))) {  
  324.             if (!(ftp.makeDirectory(subdir)))  
  325.             {  
  326.               int rc = ftp.getReplyCode();  
  327.               if (((rc != 550) && (rc != 553) && (rc != 521)))  
  328.               {  
  329.                 throw new IOException("could not create directory: " + ftp.getReplyString());  
  330.               }  
  331.             }  
  332.             else {  
  333.               ftp.changeWorkingDirectory(subdir);  
  334.             }  
  335.           }  
  336.         }  
  337.         if (workingDirectory != null){  
  338.           ftp.changeWorkingDirectory(workingDirectory);  
  339.         }  
  340.       }  
  341.   
  342.       
  343.       
  344.       
  345.       
  346.       
  347.       
  348.       
  349.       
  350.     /** 
  351.      * 获取指定目录下的文件名称列表 
  352.      * @param currentDir 
  353.      *            需要获取其子目录的当前目录名称 
  354.      * @return 返回子目录字符串数组 
  355.      */  
  356.     public String[] GetFileNames(FTPClient ftpClient,String currentDir) {  
  357.         String[] dirs = null;  
  358.         try {  
  359.             if (currentDir == null)  
  360.                 dirs = ftpClient.listNames();  
  361.             else  
  362.                 dirs = ftpClient.listNames(currentDir);  
  363.         } catch (IOException e) {  
  364.             e.printStackTrace();  
  365.         }  
  366.         return dirs;  
  367.     }  
  368.   
  369.     /** 
  370.      * 获取指定目录下的文件与目录信息集合 
  371.      * @param currentDir 
  372.      *            指定的当前目录 
  373.      * @return 返回的文件集合 
  374.      */  
  375.     public FTPFile[] GetDirAndFilesInfo(FTPClient ftpClient,String currentDir)  
  376.     {  
  377.         FTPFile[] files = null;  
  378.         try  
  379.         {  
  380.             if (currentDir == null)  
  381.                 files = ftpClient.listFiles();  
  382.             else  
  383.                 files = ftpClient.listFiles(currentDir);  
  384.         }  
  385.         catch (IOException ex)  
  386.         {  
  387.             ex.printStackTrace();  
  388.         }  
  389.         return files;  
  390.     }  
  391. }  

 

 

 

Java代码  收藏代码
  1. package easyway.tbs.transfer.ftp;  
  2.   
  3. import easyway.tbs.commons.EnumUtils;  
  4.   
  5. /** 
  6.  * 文件下载状态 
  7.  * @author longgangbai 
  8.  * 
  9.  */  
  10. public enum DownloadStatus {  
  11.          
  12.         Remote_File_Noexist(0,"远程文件不存在"), // 远程文件不存在   
  13.         //用于单个下载  
  14.         Download_New_Success(1,"下载文件成功"), // 下载文件成功  
  15.         Download_New_Failed(2,"下载文件失败"), // 下载文件失败  
  16.         Local_Bigger_Remote(3,"本地文件大于远程文件"), // 本地文件大于远程文件  
  17.         Download_From_Break_Success(4,"文件断点续传成功"), // 断点续传成功  
  18.         Download_From_Break_Failed(5,"文件断点续传失败"), // 断点续传失败  
  19.         //用于批量下载  
  20.         Download_Batch_Success(6,"文件批量下载成功"),  
  21.         Download_Batch_Failure(7,"文件批量下载失败"),  
  22.         Download_Batch_Failure_SUCCESS(8,"文件批量下载不完全成功");  
  23.       
  24.         private int code;  
  25.           
  26.         private String description;  
  27.           
  28.           
  29.         private DownloadStatus(int code , String description) {  
  30.             this.code = code;  
  31.             this.description = description;  
  32.         }  
  33.   
  34.         public int getCode() {  
  35.             return code;  
  36.         }  
  37.   
  38.         public void setCode(int code) {  
  39.             this.code = code;  
  40.         }  
  41.   
  42.         public String getDescription() {  
  43.             return description;  
  44.         }  
  45.   
  46.         public void setDescription(String description) {  
  47.             this.description = description;  
  48.         }  
  49.           
  50.         /** 
  51.          * 下载状态中中使用的code 
  52.          * @param code 
  53.          * @return 
  54.          */  
  55.         public static DownloadStatus fromCode(int code) {  
  56.             return EnumUtils.fromEnumProperty(DownloadStatus.class"code", code);  
  57.         }  
  58.     }  

 

 

 

Java代码  收藏代码
  1. package easyway.tbs.transfer.ftp;  
  2.   
  3. import easyway.tbs.commons.EnumUtils;  
  4.   
  5. /** 
  6.  * 文件上传状态 
  7.  * @author longgangbai 
  8.  * 
  9.  */  
  10. public enum UploadStatus {  
  11.     Create_Directory_Fail(0,"远程服务器相应目录创建失败"), // 远程服务器相应目录创建失败  
  12.     Create_Directory_Success(1,"远程服务器闯将目录成功"), // 远程服务器闯将目录成功  
  13.     Upload_New_File_Success(2,"上传新文件成功"), // 上传新文件成功  
  14.     Upload_New_File_Failed(3,"上传新文件失败"), // 上传新文件失败  
  15.     File_Exits(4,"文件已经存在"), // 文件已经存在  
  16.     Remote_Bigger_Local(5,"远程文件大于本地文件"), // 远程文件大于本地文件  
  17.     Upload_From_Break_Success(6," 断点续传成功"), // 断点续传成功  
  18.     Upload_From_Break_Failed(7,"断点续传失败"), // 断点续传失败  
  19.     Delete_Remote_Faild(8,"删除远程文件失败"); // 删除远程文件失败  
  20.       
  21.     private int code;  
  22.       
  23.     private String description;  
  24.       
  25.       
  26.     private UploadStatus(int code , String description) {  
  27.         this.code = code;  
  28.         this.description = description;  
  29.     }  
  30.   
  31.     public int getCode() {  
  32.         return code;  
  33.     }  
  34.   
  35.     public void setCode(int code) {  
  36.         this.code = code;  
  37.     }  
  38.   
  39.     public String getDescription() {  
  40.         return description;  
  41.     }  
  42.   
  43.     public void setDescription(String description) {  
  44.         this.description = description;  
  45.     }  
  46.       
  47.     /** 
  48.      * 下载状态中中使用的code 
  49.      * @param code 
  50.      * @return 
  51.      */  
  52.     public static UploadStatus fromCode(int code) {  
  53.         return EnumUtils.fromEnumProperty(UploadStatus.class"code", code);  
  54.     }  
  55. }  

 

Java代码  收藏代码
  1. package easyway.tbs.commons;  
  2.   
  3. import org.apache.commons.lang.ObjectUtils;  
  4. import org.apache.log4j.Logger;  
  5.   
  6. /** 
  7.  * 枚举的工具类 
  8.  * @author longgangbai 
  9.  * 
  10.  */  
  11. public abstract class EnumUtils {  
  12.     private static final Logger logger = Logger.getLogger(EnumUtils.class);  
  13.   
  14.         /** 
  15.      * 从指定的枚举类中根据property搜寻匹配指定值的枚举实例 
  16.      * @param <T> 
  17.      * @param enumClass 
  18.      * @param property 
  19.      * @param propValue 
  20.      * @return 
  21.      */  
  22.     public static <T extends Enum<T>> T fromEnumProperty(Class<T> enumClass, String property, Object propValue) {  
  23.         T[] enumConstants = enumClass.getEnumConstants();  
  24.         for (T t : enumConstants) {  
  25.             Object constantPropValue;  
  26.             try {  
  27.                 constantPropValue = BeanUtils.getDeclaredFieldValue(t, property);  
  28.                 if (ObjectUtils.equals(constantPropValue, propValue)) {  
  29.                     return t;  
  30.                 }  
  31.             } catch (Exception e) {  
  32.                 logger.error(e.getMessage());  
  33.                 throw new RuntimeException(e);  
  34.             }  
  35.         }  
  36.         return null;  
  37.     }  
  38.   
  39.     /** 
  40.      * 从指定的枚举类中根据名称匹配指定值 
  41.      * @param <T> 
  42.      * @param enumClass 
  43.      * @param constantName 
  44.      * @return 
  45.      */  
  46.     public static <T extends Enum<T>> T fromEnumConstantName(Class<T> enumClass, String constantName) {  
  47.         T[] enumConstants = enumClass.getEnumConstants();  
  48.         for (T t : enumConstants) {  
  49.             if (((Enum<?>) t).name().equals(constantName)) {  
  50.                 return t;  
  51.             }  
  52.         }  
  53.         return null;  
  54.     }  
  55.       
  56. }  

 

 

Java代码  收藏代码
  1. package easyway.tbs.commons;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileOutputStream;  
  5. import java.io.OutputStream;  
  6. import java.util.Collection;  
  7.   
  8. import org.apache.commons.io.FileUtils;  
  9. import org.apache.commons.io.IOCase;  
  10. import org.apache.commons.io.IOUtils;  
  11. import org.apache.commons.io.filefilter.FalseFileFilter;  
  12. import org.apache.commons.io.filefilter.FileFilterUtils;  
  13. import org.apache.commons.io.filefilter.IOFileFilter;  
  14. import org.apache.log4j.Logger;  
  15. /** 
  16.  * 文件操作工具类 
  17.  *  
  18.  * @author longgangbai 
  19.  *  
  20.  */  
  21. public class FileOperateUtils {  
  22.       
  23.     private static final Logger logger = Logger.getLogger(FileOperateUtils.class);    
  24.     /** 
  25.      * 查找需要合并文件的临时文件信息  
  26.      *  
  27.      * @param directory 
  28.      *          临时文件所在的目录 
  29.      * @param prefix 
  30.      *          临时文件的前缀 
  31.      * @param caseSensitivity 
  32.      *          临时文件的大小写敏感 
  33.      * @return 
  34.      */  
  35.     public static Collection<File> searchPrefixFile(File directory,String prefix,boolean caseSensitivity){  
  36.         IOCase iocase=IOCase.INSENSITIVE;  
  37.         if(caseSensitivity){  
  38.              iocase=IOCase.SENSITIVE;  
  39.         }  
  40.         //创建相关的过滤器  
  41.         IOFileFilter fileFilter=FileFilterUtils.prefixFileFilter(prefix, iocase);  
  42.         //检查相关的过滤信息  
  43.         return FileUtils.listFiles(directory, fileFilter, FalseFileFilter.INSTANCE);  
  44.     }  
  45.       
  46.     /** 
  47.      *  查找目录下特定后缀的文件 
  48.      * @param directory     
  49.      *       特定的目录 
  50.      * @param extensions 
  51.      *      临时文件的后缀扩展 
  52.      * @param recursive 
  53.      *      是否查询临时文件所在的目录下的子目录 
  54.      * @return 
  55.      */  
  56.     public static Collection<File> searchExtensionFile(File directory,String[] extensions,boolean recursive){  
  57.         return FileUtils.listFiles(directory, extensions, recursive);  
  58.     }  
  59.     /** 
  60.      * 文件追加功能 
  61.      * @param lines 
  62.      * @param tmpFilePath 
  63.      */  
  64.     public static void writeLinesToFile(Collection<String> lines,String tmpFilePath){  
  65.         OutputStream output=null;  
  66.         try {  
  67.             output = new FileOutputStream(tmpFilePath,true);  
  68.             IOUtils.writeLines(lines, "UTF-8", output);  
  69.         } catch (Exception e) {  
  70.             logger.error(tmpFilePath+"追加文件失败"+e.getMessage());  
  71.         }  
  72.           
  73.     }  
  74. }  

 

分享到:  
Java 分割功能实现 | ORA-19809: 超出了恢复文件数的限制故障处 ...
  • 2011-08-25 08:30
  • 浏览 3967
  • 评论(5)
  • 分类:开源软件
  • 相关推荐
评论
5 楼 fym548 2014-11-14  
下载乱码需要怎么做?
4 楼 fym548 2014-11-14  
上传中文乱码怎么处理?
3 楼 yuaihui 2013-11-08  
 FileOperateUtils、EnumUtils求同
2 楼 longgangbai 2012-11-19  
FileOperateUtils、EnumUtils怎么都没有?这两个类自己封装的两个工具类.已经在下边代码中添加,请知悉! 



1 楼 yangkai 2012-11-16  
FileOperateUtils、EnumUtils怎么都没有?
能否提供一份打包的源代码呀,谢谢!!!
alex1161596325@gmail.com
发表评论

 您还没有登录,请您登录后再发表评论

longgangbai
  • 浏览: 2795557 次
  • 性别: Icon_minigender_1
  • 来自: 上海
最近访客 更多访客>>
wu54gzw
goed
jsondu
u010523832
文章分类
  • 全部博客 (1546)
  • 企业中间件 (236)
  • 企业应用面临的问题 (236)
  • 小布Oracle学习笔记汇总 (36)
  • Spring 开发应用 (54)
  • IBatis开发应用 (16)
  • Oracle基础学习 (23)
  • struts2.0 (41)
  • JVM&ClassLoader&GC (16)
  • JQuery的开发应用 (17)
  • WebService的开发应用 (21)
  • Java&Socket (44)
  • 开源组件的应用 (254)
  • 常用Javascript的开发应用 (28)
  • J2EE开发技术指南 (163)
  • EJB3开发应用 (11)
  • GIS&Mobile&MAP (36)
  • SWT-GEF-RCP (52)
  • 算法&数据结构 (6)
  • Apache开源组件研究 (62)
  • Hibernate 学习应用 (57)
  • java并发编程 (59)
  • MySQL&Mongodb&MS/SQL (15)
  • Oracle数据库实验室 (55)
  • 搜索引擎的开发应用 (34)
  • 软件工程师笔试经典 (14)
  • 其他杂项 (10)
  • AndroidPn& MQTT&C2DM&推技术 (29)
  • ActiveMQ学习和研究 (38)
  • Google技术应用开发和API分析 (11)
  • flex的学习总结 (59)
  • 项目中一点总结 (20)
  • java疑惑 java面向对象编程 (28)
  • Android 开发学习 (133)
  • linux和UNIX的总结 (37)
  • Titanium学习总结 (20)
  • JQueryMobile学习总结 (34)
  • Phonegap学习总结 (32)
  • HTML5学习总结 (41)
  • JeeCMS研究和理解分析 (9)
社区版块
  • 我的资讯 (0)
  • 我的论坛 (92)
  • 我的问答 (6)
存档分类
  • 2014-06 (10)
  • 2014-01 (8)
  • 2013-12 (16)
  • 更多存档...
最新评论
  • qq_28108539: 您好,为什么我的activemq.xml文件配置完MySql持 ...
    ActiveMQ消息持久化到数据库
  • u011714701:      ;太感谢博主了。研究了一天,终于在博主这看到方法了。 ...
    Android文件图片上传的详细讲解(一)HTTP multipart/form-data 上传报文格式实现手机端上传
  • loyin: 请教个问题,由于我的流程里全部是servicetask 但我的 ...
    工作流Activiti的学习总结(八)Activiti自动执行的应用
  • liaokangli: 这段代码有必要的吧!申请读锁之后,其它等待读的线程就可以进行读 ...
    java 中 ReentrantReadWriteLock的读锁和写锁的使用
  • u012724947: 我可以连接  为什么发消息就失败
    MQTT的学习研究(十三) IBM MQTTV3 简单发布订阅实例
0 0
原创粉丝点击