Commons-net FTPClient上传下载的封装

在项目中使用到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.     }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值