FTP 断点续传工具

来源:互联网 发布:java如何实现权限管理 编辑:程序博客网 时间:2024/05/20 18:03

**
* 类描述: 文件断点续传工具类
* @author:赵博
* @since:2017-6-14 下午13:41
* @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
*
*
*/
public class ContinueFTP2 {

 public FTPClient ftpClient = new FTPClient();  private String ftpURL,username,pwd,ftpport,file1,file2;  /******  *   * @param _ftpURL     文件服务器长传地址  * @param _username   用户名  * @param _pwd        密码  * @param _ftpport    端口  * @param _file1            要传输的文件  * @param _file2            目的文件夹  */ public ContinueFTP2(String _ftpURL,String _username,String _pwd,String _ftpport,String _file1,String _file2 ){           //设置将过程中使用到的命令输出到控制台        ftpURL = _ftpURL;      username = _username;      pwd = _pwd;      ftpport = _ftpport;      file1 = _file1;      file2 = _file2;      ftpClient.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));       }      /**      * 连接到FTP服务器       * @param hostname 主机名       * @param port 端口       * @param username 用户名       * @param password 密码       * @return 是否连接成功       * @throws IOException       */      public boolean connect(String hostname,int port,String username,String password) throws IOException{           ftpClient.connect(hostname, port);           ftpClient.setControlEncoding("GBK");           if(FTPReply.isPositiveCompletion(ftpClient.getReplyCode())){               if(ftpClient.login(username, password)){                   return true;               }           }           disconnect();           return false;       }      /** *//**       * 断开与远程服务器的连接       * @throws IOException       */      public void disconnect() throws IOException{           if(ftpClient.isConnected()){               ftpClient.disconnect();           }       }     /** *//**       * 递归创建远程服务器目录       * @param remote 远程服务器文件绝对路径       * @param ftpClient FTPClient 对象       * @return 目录创建是否成功       * @throws IOException       */      public UploadStatus CreateDirecroty(String remote,FTPClient ftpClient) throws IOException{           UploadStatus status = UploadStatus.Create_Directory_Success;           String directory = remote.substring(0,remote.lastIndexOf("/")+1);           if(!directory.equalsIgnoreCase("/")&&!ftpClient.changeWorkingDirectory(new String(directory.getBytes("GBK"),"iso-8859-1"))){               //如果远程目录不存在,则递归创建远程服务器目录               int start=0;               int end = 0;               if(directory.startsWith("/")){                   start = 1;               }else{                   start = 0;               }               end = directory.indexOf("/",start);               while(true){                   String subDirectory = new String(remote.substring(start,end).getBytes("GBK"),"iso-8859-1");                   if(!ftpClient.changeWorkingDirectory(subDirectory)){                       if(ftpClient.makeDirectory(subDirectory)){                           ftpClient.changeWorkingDirectory(subDirectory);                       }else {                           System.out.println("创建目录失败");                           return UploadStatus.Create_Directory_Fail;                       }                   }                   start = end + 1;                   end = directory.indexOf("/",start);                   //检查所有目录是否创建完毕                   if(end <= start){                       break;                   }               }           }           return status;       }    /** *//**       * 上传文件到服务器,新上传和断点续传       * @param remoteFile 远程文件名,在上传之前已经将服务器工作目录做了改变       * @param localFile 本地文件 File句柄,绝对路径       * @param processStep 需要显示的处理进度步进值       * @param ftpClient FTPClient 引用       * @return       * @throws IOException       */      public UploadStatus uploadFile(String remoteFile,File localFile,FTPClient ftpClient,long remoteSize) throws IOException{           UploadStatus status;           //显示进度的上传           long step = localFile.length() / 100;           long process = 0;           long localreadbytes = 0L;           RandomAccessFile raf = new RandomAccessFile(localFile,"r");           OutputStream out = ftpClient.appendFileStream(new String(remoteFile.getBytes("GBK"),"iso-8859-1"));           //断点续传           if(remoteSize>0){               ftpClient.setRestartOffset(remoteSize);               process = remoteSize /step;               raf.seek(remoteSize);               localreadbytes = remoteSize;           }           byte[] bytes = new byte[1024];           int c;           while((c = raf.read(bytes))!= -1){               out.write(bytes,0,c);               localreadbytes+=c;               if(localreadbytes / step != process){                   process = localreadbytes / step;                   System.out.println("上传进度:" + process);                   //TODO 汇报上传状态               }           }           out.flush();           raf.close();           out.close();           boolean result =ftpClient.completePendingCommand();           if(remoteSize > 0){               status = result?UploadStatus.Upload_From_Break_Success:UploadStatus.Upload_From_Break_Failed;           }else {               status = result?UploadStatus.Upload_New_File_Success:UploadStatus.Upload_New_File_Failed;           }           return status;       }     public void downloadFile(String remote,String local){        try{            FTPFile[] filelist=ftpClient.listFiles(remote);            FTPFile ftpFile = null;            String category = null;            int length = filelist.length;            for (int i = 0; i < length; i++) {                ftpFile = filelist[i];                category = ftpFile.getName();                if(ftpFile.isFile()){                    download(remote+category, local+category);                }else{                    String wjj=local+category;                    File file=new File(wjj);                    if(file.exists()){                        downloadFile(remote+category+"//", local+category+"\\");                    }else{                        if(file.mkdir()){                            downloadFile(remote+category+"//", local+category+"\\");                        }                    }                }            }        }catch(Exception e){            System.out.println(e.getMessage());        }    }    /** *//**       * 从FTP服务器上下载文件,支持断点续传,上传百分比汇报       * @param remote 远程文件路径       * @param local 本地文件路径       * @return 上传的状态       * @throws IOException       */      public DownloadStatus download(String remote,String local) throws IOException{           //设置被动模式           ftpClient.enterLocalPassiveMode();           //设置以二进制方式传输           ftpClient.setFileType(FTP.BINARY_FILE_TYPE);           DownloadStatus result;           //检查远程文件是否存在           FTPFile[] files = ftpClient.listFiles(new String(remote.getBytes("GBK"),"iso-8859-1"));           if(files.length != 1){               System.out.println("远程文件不存在");               return DownloadStatus.Remote_File_Noexist;           }           long lRemoteSize = files[0].getSize();           File f = new File(local);           //本地存在文件,进行断点下载           if(f.exists()){               long localSize = f.length();               //判断本地文件大小是否大于远程文件大小               if(localSize >= lRemoteSize){                   System.out.println("本地文件大于远程文件,下载中止");                   return DownloadStatus.Local_Bigger_Remote;               }               //进行断点续传,并记录状态               FileOutputStream out = new FileOutputStream(f,true);               ftpClient.setRestartOffset(localSize);               InputStream in = ftpClient.retrieveFileStream(new String(remote.getBytes("GBK"),"iso-8859-1"));               byte[] bytes = new byte[1024];               long step = lRemoteSize /100;               long process=localSize /step;               int c;               while((c = in.read(bytes))!= -1){                   out.write(bytes,0,c);                   localSize+=c;                   long nowProcess = localSize /step;                   if(nowProcess > process){                       process = nowProcess;                       if(process % 10 == 0)                           System.out.println("下载进度:"+process);                       //TODO 更新文件下载进度,值存放在process变量中                   }               }               in.close();               out.close();               boolean isDo = ftpClient.completePendingCommand();               if(isDo){                   result = DownloadStatus.Download_From_Break_Success;               }else {                   result = DownloadStatus.Download_From_Break_Failed;               }           }else {               OutputStream out = new FileOutputStream(f);               InputStream in= ftpClient.retrieveFileStream(new String(remote.getBytes("GBK"),"iso-8859-1"));               byte[] bytes = new byte[1024];               long step = lRemoteSize /100;               long process=0;               long localSize = 0L;               int c;               while((c = in.read(bytes))!= -1){                   out.write(bytes, 0, c);                   localSize+=c;                   long nowProcess = localSize /step;                   if(nowProcess > process){                       process = nowProcess;                       if(process % 10 == 0)                           System.out.println("下载进度:"+process);                       //TODO 更新文件下载进度,值存放在process变量中                   }               }               in.close();               out.close();               boolean upNewStatus = ftpClient.completePendingCommand();               if(upNewStatus){                   result = DownloadStatus.Download_New_Success;               }else {                   result = DownloadStatus.Download_New_Failed;               }           }           return result;       }     public void moveFTPFile(FTPClient ftpClient, String from, String to){        boolean result=true;        try {            FTPFile[] filelist=ftpClient.listFiles(from);            FTPFile ftpFile = null;            String category = null;            int length = filelist.length;            for (int i = 0; i < length; i++) {                ftpFile = filelist[i];                category = ftpFile.getName();                if (ftpFile.isFile()) {                    ftpClient.rename(from+category, to+category);                }else{                    ftpClient.rename(from+category, to+category);                    //moveFTPFile(ftpClient,from+category+"//",to+"//");                }            }        } catch (IOException e) {            // TODO 自动生成的 catch 块            e.printStackTrace();        }    }    public  boolean copyFTPFile(FTPClient ftpClient, String from, String to){        boolean copyFalg = false;        FTPFile[] filelist;        try {            // 枚举当前from目录所有文件+子目录            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);            ftpClient.enterLocalPassiveMode();            filelist = ftpClient.listFiles(from);            int length = filelist.length;            FTPFile ftpFile = null;            String category = null;            InputStream inputStream = null;            for (int i = 0; i < length; i++) {                ftpFile = filelist[i];                category = ftpFile.getName();                if (ftpFile.isFile()) {                    ftpClient.setBufferSize(1024);                       ByteArrayOutputStream fos=new ByteArrayOutputStream();                      ftpClient.retrieveFile(from, fos);                      ByteArrayInputStream in=new ByteArrayInputStream(fos.toByteArray());                      ftpClient.storeFile(to, in);                      fos.close();                      in.close();                } else if (ftpFile.isDirectory()) {                    // 如果是目录则先创建该目录                   // copyFalg = ftpClient.makeDirectory(to);                    // 再进入子目录进行递归复制                    //copyDirectory(ftpClient, from , to);                }            }        } catch (IOException e) {           // logger.error("FtpClientUtil.copyDirectory failed. caused by " + e.getMessage(), e);            copyFalg = false;        }        return copyFalg;    }    public boolean delete(FTPClient ftpClient,String deltefile){        try {            ftpClient.deleteFile(deltefile);        } catch (IOException e) {            // TODO 自动生成的 catch 块            e.printStackTrace();        }        return true;    }    public static void main(String args[]){        try {            ContinueFTP2 ftp=new ContinueFTP2("192.168.7.24", "username", "password", "21", null, null);            boolean isconnect=ftp.connect("192.168.7.24", 21, "username", "password");            String from="//CloudStation//web-tps-file//pinncal//pending//";            String to="//CloudStation//web-tps-file//pinncal//alreadyDeal//";            String resulttpssb="//CloudStation//web-tps-file//pinncal//result//deal-fail//";            String resulttpscg="//CloudStation//web-tps-file//pinncal//result//deal-succeed//";            String tbcg="E:\\信息中心研发部\\开发项目文档\\架构设计文档\\网页自动计划\\云端TPS文件区域\\result\\deal-succeed\\";            String tbsb="E:\\信息中心研发部\\开发项目文档\\架构设计文档\\网页自动计划\\云端TPS文件区域\\result\\deal-fail\\";            if(isconnect){                long remotesize=1024L;                ftp.downloadFile(resulttpssb,tbsb);                //ftp.moveFTPFile(ftp.ftpClient, from, from, to);                ftp.downloadFile(resulttpscg,tbcg);                //ftp.moveFTPFile(ftp.ftpClient, from, to);                //ftp.copyFTPFile(ftp.ftpClient, from,to);            //  ftp.delete(ftp.ftpClient, from);                //ftp.uploadFile("//CloudStation//web-tps-file//pinncal//1.xlsx", new File("C:\\Users\\Allcure\\Downloads\\1.xlsx"), ftp.ftpClient, remotesize);            }        } catch (IOException e) {            // TODO 自动生成的 catch 块            e.printStackTrace();        }    }
原创粉丝点击