ftp4j 实现 上传下载 代理 断点续传

来源:互联网 发布:自媒体平台 知乎 编辑:程序博客网 时间:2024/04/27 10:43
<pre name="code" class="java">import it.sauronsoftware.ftp4j.FTPAbortedException;import it.sauronsoftware.ftp4j.FTPClient;import it.sauronsoftware.ftp4j.FTPDataTransferException;import it.sauronsoftware.ftp4j.FTPException;import it.sauronsoftware.ftp4j.FTPFile;import it.sauronsoftware.ftp4j.FTPIllegalReplyException;import it.sauronsoftware.ftp4j.FTPListParseException;import it.sauronsoftware.ftp4j.connectors.HTTPTunnelConnector;import it.sauronsoftware.ftp4j.connectors.SOCKS4Connector;import it.sauronsoftware.ftp4j.connectors.SOCKS5Connector;import java.io.ByteArrayInputStream;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.Date;import java.util.regex.Matcher;import java.util.regex.Pattern;import com.primeton.esb.common.log.ILogger; import com.primeton.esb.common.log.LoggerFactory;/**   * @Description: TODO  * @author ZhangHuan   * @date 2014-3-10 下午2:56:21     */public class FTPToolkits {protected  ILogger logger = LoggerFactory.getInstance().getLogger(getClass());private FTPPathToolkit ftpPathTookit=new FTPPathToolkit();/**    * <p>Title: </p>    * <p>Description: </p>      */ public FTPToolkits() {super();// TODO Auto-generated constructor stub}/** *   * @Title: connectFtpConnection    * @Description: 连接ftp服务器  * @param @param host  * @param @param port  * @param @param username  * @param @param password  * @param @param prosyIp  * @param @param proxyPort  * @param @return  * @param @throws IllegalStateException  * @param @throws IOException  * @param @throws FTPIllegalReplyException  * @param @throws FTPException  * @param @throws FTPDataTransferException  * @param @throws FTPAbortedException  * @param @throws FTPListParseException       * @return FTPClient     * @throws */ public  FTPClient connectFtpConnection(String host, int port, String username, String password,String prosyIp,Integer proxyPort,String proxyuserName,String proxyPassword,int proxy_type) throws IllegalStateException, IOException, FTPIllegalReplyException, FTPException, FTPDataTransferException, FTPAbortedException, FTPListParseException {          FTPClient client = new FTPClient();                 if(proxy_type==1){        SOCKS4Connector socks4 = new SOCKS4Connector(prosyIp, proxyPort);         client.setConnector(socks4);         }         else if(proxy_type==2){         SOCKS5Connector socks5 = new SOCKS5Connector(prosyIp, proxyPort,proxyuserName,proxyPassword);                    client.setConnector(socks5);         }         else if(proxy_type==3){         if(proxyuserName==null||"".equals(proxyuserName)||proxyPassword==null||"".equals(proxyPassword)){         HTTPTunnelConnector http=new HTTPTunnelConnector(prosyIp, proxyPort);            client.setConnector(http);         }         if(proxyuserName!=null&&!"".equals(proxyuserName)&&proxyPassword!=null&&!"".equals(proxyPassword)){         HTTPTunnelConnector http=new HTTPTunnelConnector(prosyIp, proxyPort,proxyuserName,proxyPassword);                 client.setConnector(http);         }         }         client.connect(host, port);         client.login(username, password);         client.setType(FTPClient.TYPE_BINARY);         client.setCharset("gbk");         return client;          }   /**         * FTP上传本地文件到FTP的一个目录下         *         * @param client                     FTP客户端         * @param localfile                本地文件         * @param remoteFolderPath FTP上传目录  * @throws Exception         */        public  void upload(FTPClient client,  ArrayList<File> localfile_list, String remoteFolderPath,String reName,int sameNameHandle) throws Exception {        FTPFile [] remote_file_list=null;       FTPFile remote_file=null;       // File destFile=null;       String temp_reName=reName;       boolean upload_flag=false;//判断上传是否成功标记             remoteFolderPath = ftpPathTookit.formatPathFTP(remoteFolderPath);             boolean flags=false;//远程保存文件路径是否存在标记               try {               flags=exists(client, remoteFolderPath);               } catch (Exception e2) {throw new Exception("AbstractFtpEndpointComponent  upload  make sure remoteFolderPath  exits  error");               }            if(!flags){try {client.createDirectory(remoteFolderPath);} catch (Exception e) {// TODO Auto-generated catch blockthrow new Exception("AbstractFtpEndpointComponent  upload  create directory fail");}            }               //FTPListener listener = FTPListener.instance(FTPOptType.UP,client);                try {                    client.changeDirectory(remoteFolderPath);                    remote_file_list=client.list();                  synchronized(this){                 for(File localfile: localfile_list){  //遍历上传的每个文件outer for                     if(localfile_list.size()>1){                     temp_reName=localfile.getName();                         }else{                         if(temp_reName==null||"".equals(temp_reName)){                               temp_reName=localfile.getName();                               }                         }                    if(remote_file_list.length>0){                       boolean flag=false;//标记是否断点下载                        for(int i=0;i<remote_file_list.length;i++){                    //if continue upload                          if(remote_file_list[i].getName().equals(temp_reName+".up")){//inner if begin                            flag=true;                           remote_file=remote_file_list[i];                           break;                           }                       if(remote_file_list[i].getName().equals(temp_reName)){                                                      if(sameNameHandle==1){                               SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss-SSS");                                   Date date = new Date();                               if(temp_reName.contains("-")){                               temp_reName=temp_reName.substring(0,temp_reName.indexOf("-")+1)+df.format(date)+temp_reName.substring(temp_reName.indexOf("."));                               }else{                               temp_reName=temp_reName.substring(0,temp_reName.indexOf("."))+"-"+df.format(date)+temp_reName.substring(temp_reName.indexOf("."));                               }                               }                               break;                       }                                               }//inner  for end                        if(flag){//断点续传                       long remote_file_size=remote_file.getSize();                        //if (listener != null) {                       InputStream inputStream = null;                       try {                       inputStream = new FileInputStream(localfile);                       } catch (IOException e) {                       throw new Exception("AbstractFtpEndpointComponent  upload  continue upload error:"+e.getMessage());                                              }                       client.upload(temp_reName+".up", inputStream, remote_file_size, remote_file_size,null);                       logger.debug("AbstractFtpEndpointComponent  upload  continue upload file success");                                upload_flag=true;                                                               /* }else{                                 InputStream inputStream = null;                       try {                       inputStream = new FileInputStream(localfile);                       } catch (IOException e) {                       throw new FTPDataTransferException(e);                       }                       client.upload(temp_reName+".up", inputStream, remote_file_size,remote_file_size,null);                                upload_flag=true;                                }*/                       }else{// flag if end 非断点上传                       // if (listener != null) {                                //如何重命名                       InputStream inputStream = null;                   try {                   inputStream = new FileInputStream(localfile);                   } catch (IOException e) {                   throw new Exception("AbstractFtpEndpointComponent  upload not continue uploadfile  error:"+e.getMessage());                   }                   client.upload(temp_reName+".up", inputStream, 0,0,null);                   logger.debug("AbstractFtpEndpointComponent  upload  not continue upload file success");                            upload_flag=true;                                                    /*   }                           else{                                                    InputStream inputStream = null;                   try {                   inputStream = new FileInputStream(localfile);                   } catch (IOException e) {                   throw new FTPDataTransferException(e);                   }                   client.upload(temp_reName+".up", inputStream, 0,0,null);                            upload_flag=true;                                                    }*/                                                  }                       if(upload_flag){//上传成功后对上传文件更正名称                       client.rename(ftpPathTookit.formatPathFile(remoteFolderPath+File.separator+temp_reName+".up"),                       ftpPathTookit.formatPathFile(remoteFolderPath+File.separator+temp_reName));                       }                     }// if(remote_file_list.length>0) if end                                    }//for end outer                  }// tongbu                  client.changeDirectory(File.separator);                } catch (Exception e) {             throw new Exception("AbstractFtpEndpointComponent  upload  uploadfile fail:"+e.getMessage());               }       }               /**         * FTP上传本地文件到FTP的一个目录下         *         * @param client                     FTP客户端         * @param localfilepath        本地文件路径         * @param remoteFolderPath FTP上传目录      * @throws Exception         */        public  boolean  upload(FTPClient client, String localfilepath, String remoteFolderPath,String local_file_Name,String reName,       int sameNameHandle) throws Exception {        File localfile =new File(localfilepath);       String regexp="";       //如果不是文件夹        if(!localfile.exists()){        throw new Exception(" AbstractFtpEndpointComponent upload localFilePath not exits");           }       if(local_file_Name!=null&&!"".equals(local_file_Name)){//上传的是否文件夹       FileSearcher fileSearcher=new FileSearcher();       regexp=fileSearcher.wildcardToRegexp(local_file_Name);                 Pattern p = Pattern.compile(regexp);         ArrayList<File> file_list=fileSearcher.filePattern(localfile, p);       if(file_list.size()==0){       throw new Exception("AbstractFtpEndpointComponent upload  file not  exits");       }               upload(client, file_list, remoteFolderPath,reName,sameNameHandle);               return true;       }else{//文件夹上传       if(localfile.exists()){       try {uploadFolder(client ,remoteFolderPath,localfile,sameNameHandle);return true;} catch (Exception e) {// TODO Auto-generated catch blockthrow new Exception("AbstractFtpEndpointComponent upload  uploadFolder fail");}       }       }return false;       }        /**         * FTP上传本地文件到FTP的一个目录下         *         * @param client                     FTP客户端         * @param localfilepath        本地文件路径         * @param remoteFolderPath FTP上传目录      * @throws Exception         */        public  boolean  upload(FTPClient client, byte[] payload,String remoteFolderPath,String reName,       int sameNameHandle) throws Exception {     FTPFile [] remote_file_list=null;       FTPFile remote_file=null;       // File destFile=null;       String temp_reName=reName;       boolean upload_flag=false;//判断上传是否成功标记             remoteFolderPath = ftpPathTookit.formatPathFTP(remoteFolderPath);             boolean flags=false;//远程保存文件路径是否存在标记               try {               flags=exists(client, remoteFolderPath);               } catch (Exception e2) {throw new Exception("AbstractFtpEndpointComponent  upload  make sure remoteFolderPath  exits  error");               }            if(!flags){try {client.createDirectory(remoteFolderPath);} catch (Exception e) {// TODO Auto-generated catch blockthrow new Exception("AbstractFtpEndpointComponent  upload  create directory fial");}            }                           try {                    client.changeDirectory(remoteFolderPath);                    remote_file_list=client.list();                  synchronized(this){                    if(remote_file_list.length>0){                       boolean flag=false;//标记是否断点下载                        for(int i=0;i<remote_file_list.length;i++){                    //if continue upload                          if(remote_file_list[i].getName().equals(temp_reName+".up")){//inner if begin                            flag=true;                           remote_file=remote_file_list[i];                           break;                           }                       if(remote_file_list[i].getName().equals(temp_reName)){                                                      if(sameNameHandle==1){                               SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss-SSS");                                   Date date = new Date();                               if(temp_reName.contains("-")){                               temp_reName=temp_reName.substring(0,temp_reName.indexOf("-")+1)+df.format(date)+temp_reName.substring(temp_reName.indexOf("."));                               }else{                               temp_reName=temp_reName.substring(0,temp_reName.indexOf("."))+"-"+df.format(date)+temp_reName.substring(temp_reName.indexOf("."));                               }                               }                               break;                       }                                               }//inner  for end                        if(flag){//断点续传                       long remote_file_size=remote_file.getSize();                        //if (listener != null) {                       InputStream inputStream = null;                       try {                       inputStream=new ByteArrayInputStream(payload);                       } catch (Exception e) {                       throw new Exception("AbstractFtpEndpointComponent  upload  continue upload error:"+e.getMessage());                                              }                       client.upload(temp_reName+".up", inputStream, remote_file_size, remote_file_size,null);                       logger.debug("AbstractFtpEndpointComponent  upload  continue upload file success");                                upload_flag=true;                                                              }else{// flag if end 非断点上传                                                     //如何重命名                       InputStream inputStream = null;                   try {                   inputStream=new ByteArrayInputStream(payload);                   } catch (Exception e) {                   throw new Exception("AbstractFtpEndpointComponent  upload not continue uploadfile  error:"+e.getMessage());                   }                   client.upload(temp_reName+".up", inputStream, 0,0,null);                   logger.debug("AbstractFtpEndpointComponent  upload  not continue upload file success");                            upload_flag=true;                                                                        }                       if(upload_flag){//上传成功后对上传文件更正名称                       client.rename(ftpPathTookit.formatPathFile(remoteFolderPath+File.separator+temp_reName+".up"),                       ftpPathTookit.formatPathFile(remoteFolderPath+File.separator+temp_reName));                       }                       return true;                    }                  }// tongbu                  client.changeDirectory(File.separator);                } catch (Exception e) {             throw new Exception("AbstractFtpEndpointComponent  upload  uploadfile fail:"+e.getMessage());               }return false;       }        /**         * 上传目录         *          * @param client         *            FTP客户端对象         * @param parentUrl         *            父节点URL         * @param file         *            目录         * @throws Exception         */         private  void uploadFolder(FTPClient client, String remote_path, File file,int sameNameHandle              ) throws Exception {         remote_path=ftpPathTookit.formatPathFile(remote_path);       try{           if (!exists(client, remote_path)) { // 判断当前目录是否存在                 client.createDirectory(remote_path);            }             client.changeDirectory(remote_path);             File[] files = file.listFiles(); // 获取当前文件夹所有文件及目录             for (int i = 0; i < files.length; i++) {             file = files[i];                 if (file.isDirectory()) { // 如果是目录,则递归上传                     uploadFolder(client,remote_path+File.separator+file.getName(), file,sameNameHandle);                 } else {                              ArrayList<File> file_list=new ArrayList<File>();               file_list.add(file);                client.changeDirectory(remote_path);                 upload(client, file_list, remote_path, null,sameNameHandle);                    }            }       }catch(Exception e){       throw new Exception("AbstractFtpEndpointComponent uploadFolder method error : "+e.getMessage());       }       }            /**         * 获取文件路径         *          * @param client         *            FTP客户端对象         * @param dir         *            文件或目录         * @return 文件路径集合        * @throws Exception         */         public   ArrayList<String>  getFilePath(FTPClient client, String remote_path,String remote_fileName) throws Exception {             FTPFile[] files = null;             ArrayList<String> fileName_list=new ArrayList<String>();           try {                 files = client.list(remote_path);             } catch (Exception e) {                 return null;             }             String name = "";             String regexp="";           for (FTPFile file : files) {                 name = file.getName();                // 排除隐藏目录                 if (".".equals(name) || "..".equals(name)) {                     continue;                 }                 if (file.getType() == FTPFile.TYPE_DIRECTORY) { //                ArrayList<String> innerlist =getFilePath(client,remote_path+File.separator+file.getName(),remote_fileName);                              fileName_list.addAll(innerlist);                    }                if (file.getType() == FTPFile.TYPE_FILE) { //                FileSearcher fileSearcher=new FileSearcher();                   regexp=fileSearcher.wildcardToRegexp(remote_fileName);                                      Pattern p = Pattern.compile(regexp);                     Matcher fMatcher = p.matcher(name);                   if(fMatcher.matches()){                   //file.get                 fileName_list.add(remote_path+File.separator+file.getName());                     }               }  //else if end                      }                          return fileName_list;           }         /**         * 获取文件路径         *          * @param client         *            FTP客户端对象         * @param dir         *            文件或目录         * @return 文件路径集合        * @throws Exception         */         public   ArrayList<FTPFile>  getRemoteFiles(FTPClient client, String remote_path,String remote_fileName) throws Exception {             FTPFile[] files = null;             ArrayList<FTPFile> fileName_list=new ArrayList<FTPFile>();           try {                 files = client.list(remote_path);             } catch (Exception e) {                 return null;             }             String name = "";             String regexp="";           for (FTPFile file : files) {                 name = file.getName();                // 排除隐藏目录                 if (".".equals(name) || "..".equals(name)) {                     continue;                 }                 if (file.getType() == FTPFile.TYPE_DIRECTORY) { //                ArrayList<FTPFile> innerlist =getRemoteFiles(client,remote_path+File.separator+file.getName(),remote_fileName);                              fileName_list.addAll(innerlist);                    }                if (file.getType() == FTPFile.TYPE_FILE) { //                FileSearcher fileSearcher=new FileSearcher();                   regexp=fileSearcher.wildcardToRegexp(remote_fileName);                                      Pattern p = Pattern.compile(regexp);                     Matcher fMatcher = p.matcher(name);                   if(fMatcher.matches()){                   //file.get                 fileName_list.add(file);                     }               }  //else if end                      }                          return fileName_list;           }         /**         * 判断当前为文件还是目录         *          * @param client         *            FTP客户端对象         * @param dir         *            文件或目录         * @return -1、文件或目录不存在 0、文件 1、目录         * @throws Exception         */         private  int getFileType(FTPClient client, String dir) throws Exception {             FTPFile[] files = null;             try {                 files = client.list(dir);             } catch (Exception e) {                 return -1;             }             if (files.length > 1) {                 return FTPFile.TYPE_DIRECTORY;             } else if (files.length == 1) {                 FTPFile f = files[0];                 if (f.getType() == FTPFile.TYPE_DIRECTORY) {                     return FTPFile.TYPE_DIRECTORY;                 }                 String path = dir + File.separator+ f.getName();                 try {                     int len = client.list(path).length;                     if (len == 1) {                         return FTPFile.TYPE_DIRECTORY;                     } else {                         return FTPFile.TYPE_FILE;                     }                 } catch (Exception e) {                     return FTPFile.TYPE_FILE;                 }             } else {                 try {                     client.changeDirectory(dir);                     client.changeDirectoryUp();                     return FTPFile.TYPE_DIRECTORY;                 } catch (Exception e) {                     return -1;                 }             }         }         /**         * 判断文件或目录是否存在         *          * @param client         *            FTP客户端对象         * @param dir         *            文件或目录         * @return         * @throws Exception         */         private boolean exists(FTPClient client, String dir) throws Exception {             return getFileType(client, dir) != -1;         }                /**         * 判断一个FTP路径是否存在,如果存在返回类型(FTPFile.TYPE_DIRECTORY=1、FTPFile.TYPE_FILE=0、FTPFile.TYPE_LINK=2)         * 如果文件不存在,则返回一个-1         *         * @param client         FTP客户端         * @param remotePath FTP文件或文件夹路径         * @return 存在时候返回类型值(文件0,文件夹1,连接2),不存在则返回-1         */        public  int isExist(FTPClient client, String remotePath) {                remotePath = ftpPathTookit.formatPathFile(remotePath);                FTPFile[] list = null;                try {                        list = client.list(remotePath);                } catch (Exception e) {                        return -1;                }                if (list.length > 1) return FTPFile.TYPE_DIRECTORY;                else if (list.length == 1) {                        FTPFile f = list[0];                        if (f.getType() == FTPFile.TYPE_DIRECTORY) return FTPFile.TYPE_DIRECTORY;                        String _path = remotePath +File.separator+ f.getName();                        try {                                int y = client.list(_path).length;                                if (y == 1) return FTPFile.TYPE_DIRECTORY;                                 else return FTPFile.TYPE_FILE;                        } catch (Exception e) {                                return  -1;                        }                } else {                        try {                                client.changeDirectory(remotePath);                                return FTPFile.TYPE_DIRECTORY;                        } catch (Exception e) {                                return -1;                        }                }        }        /**          * @param args          */   public  boolean  reName_file(File localFile,String fileName,String reName) {              // TODO 自动生成方法存根          boolean flag=false;       File rename_file=null;           String parent_path=localFile.getParent();            /*if(reName!=null){          rename_file=new File(parent_path+File.separator+reName);            if(rename_file.exists()&&reName.contains("-")){          SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss-SSS");Date date = new Date();          rename_file=new File(parent_path+File.separator+reName.substring(0,reName.indexOf("-")+1)+df.format(date)+"-1"+reName.substring(reName.lastIndexOf(".")));            }          if(rename_file.exists()&&!reName.contains("-")){          SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss-SSS");Date date = new Date();          rename_file=new File(parent_path+File.separator+reName.substring(0,reName.indexOf("-")+1)+df.format(date)+"-1"+reName.substring(reName.lastIndexOf(".")));            }           } else{           rename_file=new File(parent_path+File.separator+fileName);            if(rename_file.exists()&&fileName.contains("-")){           SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss-SSS"); Date date = new Date();           rename_file=new File(parent_path+File.separator+fileName.substring(0,fileName.indexOf("-")+1)+df.format(date)+"-1"+fileName.substring(fileName.lastIndexOf(".")));             }           if(rename_file.exists()&&!fileName.contains("-")){           SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss-SSS"); Date date = new Date();           rename_file=new File(parent_path+File.separator+fileName.substring(0,fileName.indexOf("-")+1)+df.format(date)+"-1"+fileName.substring(fileName.lastIndexOf(".")));             }           }*/           if(reName!=null){           rename_file=new File(parent_path+File.separator+reName);           }else{           rename_file=new File(parent_path+File.separator+fileName);           }           if(localFile.renameTo(rename_file))              {              flag=true;           }              return flag;              }         /**         * 删除文件或目录         *          * @param dir         *            文件或目录数组         * @throws Exception         */         public boolean delete(String dirs) throws Exception {             if (dirs==null&&"".equals(dirs)) {                 return false;             }                 File file=new File(dirs);                           return file.delete();       }             /**         * 关闭FTP连接,关闭时候像服务器发送一条关闭命令         *         * @param client FTP客户端         * @return 关闭成功,或者链接已断开,或者链接为null时候返回true,通过两次关闭都失败时候返回false      * @throws Exception         */        public boolean closeConnection(FTPClient client) throws Exception {                if (client == null) return true;                if (client.isConnected()) {                        try {                                client.disconnect(true);                                return true;                        } catch (Exception e) {                                try {                                        client.disconnect(false);                                } catch (Exception e1) {                                       throw new Exception("close client fail:"+e1.getMessage());                                                                     }                        }                }                return true;        }     }

package com.primeton.esb.component.ftp.utils;import java.io.File;/**   * @Description: TODO  * @author ZhangHuan   * @date 2014-3-10 下午3:03:57     */public class FTPPathToolkit {/**    * <p>Title: </p>    * <p>Description: </p>      */ public FTPPathToolkit() {super();// TODO Auto-generated constructor stub}/** *   * @Title: formatPath4File    * @Description:格式化文件路径,将其中不规范的分隔转换为标准的分隔符,并且去掉末尾的文件路径分隔符。  * 本方法操作系统自适应    * @param @param path  * @param @return       * @return String     * @throws */public String formatPathFile(String path) {         String reg0 = "\\\\+";         String reg = "\\\\+|/+";         String temp = path.trim().replaceAll(reg0, "/");         temp = temp.replaceAll(reg, "/");         if (temp.length() > 1 && temp.endsWith("/")) {                 temp = temp.substring(0, temp.length() - 1);         }         temp = temp.replace('/', File.separatorChar);         return temp; }/** *   * @Title: formatPathFTP    * @Description: 格式化文件路径,将其中不规范的分隔转换为标准的分隔符 ,  * 并且去掉末尾的"/"符号  * @param @param path  * @param @return       * @return String     * @throws */ public  String formatPathFTP(String path) {          String reg0 = "\\\\+";          String reg = "\\\\+|/+";          String temp = path.trim().replaceAll(reg0, "/");          temp = temp.replaceAll(reg, "/");          if (temp.length() > 1 && temp.endsWith("/")) {                  temp = temp.substring(0, temp.length() - 1);          }          return temp;  }  /**  *    * @Title: genParentPath4FTP     * @Description: 获取FTP路径的父路径,但不对路径有效性做检查    * @param @param path   * @param @return        * @return String      * @throws  */  public  String genParentPathFTP(String path) {           String parentPath = new File(path).getParent();           if (parentPath == null) return null;           else return formatPathFTP(parentPath);   } }

/**    * @Title: List_File_Searcher.java  * @Description: TODO * @author ZhangHuan    * @date 2014-3-10 下午3:24:39  * @version V1.0    */ package com.primeton.esb.component.ftp.utils;import java.io.File;import java.util.ArrayList;import java.util.regex.Matcher;import java.util.regex.Pattern;/**   * @Description: TODO  * @author ZhangHuan   * @date 2014-3-10 下午3:24:39     */public class FileSearcher { /**       * 查询指定目录下的所有文件       * @param args       */    private final char ESCAPES[] = { '$', '^', '[', ']', '(', ')', '{','|', '+', '\\', '.', '<', '>' };             /**          * 获取文件          * 可以根据正则表达式查找          * @param dir String 文件夹名称          * @param s String 查找文件名,可带*.?进行模糊查询          * @return File[] 找到的文件          */  protected  File[] getFiles(String dir,String s) {            //开始的文件夹            File file = new File(dir);            s=wildcardToRegexp(s);                /* s = s.replace('.', '#');            s = s.replaceAll("#", "\\\\.");            s = s.replace('*', '#');            s = s.replaceAll("#", ".*");            s = s.replace('?', '#');            s = s.replaceAll("#", ".?");            s = "^" + s + "$";   */           //System.out.println(s);            Pattern p = Pattern.compile(s);            ArrayList<File> list = this.filePattern(file, p);              File[] rtn = new File[list.size()];            list.toArray(rtn);            return rtn;          }            public  String wildcardToRegexp(String pattern) {   String result = "^";       for (int i = 0; i < pattern.length(); i++) {   char ch = pattern.charAt(i);   boolean isEscaped = false;   for (int j = 0; j < ESCAPES.length; j++) {   if (ch == ESCAPES[j]) {   result += "\\" + ch;   isEscaped = true;   break;   }   }       if (!isEscaped) {   if (ch == '*') {   result += ".*";   } else if (ch == '?') {   result += ".";   } else {   result += ch;   }   }   }   result += "$";   return result;   }       /**          * @param file File 起始文件夹          * @param p Pattern 匹配类型          * @return ArrayList 其文件夹下的文件夹          */           public  ArrayList<File> filePattern(File file, Pattern p) {          ArrayList<File> fileList=null;         if (file == null) {              return null;            }            else if (file.isFile()) {                    Matcher fMatcher = p.matcher(file.getName());              if (fMatcher.matches()) {              fileList = new ArrayList<File>();              fileList.add(file);                return fileList;              }                  }            else if (file.isDirectory()) {              File[] files = file.listFiles();              if (files != null && files.length > 0) {              fileList = new ArrayList<File>();                for (int i = 0; i < files.length; i++) {                  ArrayList<File> innerlist = this.filePattern(files[i], p);                  if (innerlist != null) {                  fileList.addAll(innerlist);                  }                }                return fileList;              }            }            return null;          }   }

/**    * @Title: FTPOptType.java  * @Description: TODO * @author ZhangHuan    * @date 2014-3-10 下午3:01:19  * @version V1.0    */ package com.primeton.esb.component.ftp.utils;/**   * @Description: TODO  * @author ZhangHuan   * @date 2014-3-10 下午3:01:19     */public enum FTPOptType {  UP("file upload"),       DOWN("file down");         private String optname;       FTPOptType(String optname) {               this.optname = optname;       }       public String getOptname() {               return optname;       } }
代理 这一块 用到 ccproxy 这款软件 具体使用 自己研究啦 

                                             
0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 行驶证丢了怎么办补办 行驶证丢了怎么办异地 浦发信用卡盗刷怎么办 苹果id被盗变砖怎么办 信用卡丢了被刷怎么办 ins注册不了怎么办安卓 偷玩电脑被发现怎么办 做作业不认真的怎么办 老人脑供血不足怎么办 哺乳期吃了辣的怎么办 孕32周胎位臀位怎么办 怀孕32周胎位不正怎么办 7个月胎位不正怎么办 胎心监护老不过怎么办 8个月了胎位不正怎么办 怀孕八个月了胎位不正怎么办 怀孕八个月胎位不正怎么办 欠债的人跑了怎么办 赌博输了100万怎么办 我赌博输了4万怎么办 办80张信用卡怎么办的 19岁负债十几万怎么办 欠了十几万该怎么办 网贷负债十几万怎么办 赌博欠了十几万怎么办 欠了网贷跑了会怎么办 欠银行钱还不起怎么办 欠小额贷款公司的钱还不上怎么办 负债30万没工作怎么办 华为p9耗电太快怎么办 酷派手机反应慢怎么办 网上买手机被骗了怎么办 买手机贵了怎么办12315 在手机店被骗了怎么办 在转转上被骗了怎么办 微信被骗了800怎么办 苹果6被偷走该怎么办 苹果7被偷走该怎么办 月经量突然少了怎么办 我月经老是不来怎么办 月经不来3个月怎么办