tbwshc

          文件FTP上傳支持?jǐn)帱c(diǎn)續(xù)傳demo

          package cn.eason.util.common;


          import java.io.File;
          import java.io.FileInputStream;
          import java.io.FileOutputStream;
          import java.io.IOException;
          import java.io.InputStream;
          import java.io.OutputStream;
          import java.io.PrintWriter;


          import org.apache.commons.net.PrintCommandListener;
          import org.apache.commons.net.ftp.FTP;
          import org.apache.commons.net.ftp.FTPClient;
          import org.apache.commons.net.ftp.FTPFile;
          import org.apache.commons.net.ftp.FTPReply;


          /**************************************************************
          * 文件名稱: ContinueFTP.java
          * 功能描述: ftp文件上傳功能,依賴commons-net-3.1.jar實(shí)現(xiàn)
          * 創(chuàng)建日期: 2012-5-21
          * 創(chuàng)建地址: 西安
          * 作者:  Eric.Hao
          **************************************************************/
          public class ContinueFTP {
                 
                  private FTPClient ftpClient = new FTPClient();
                 
                  public ContinueFTP(){
                         
                          //設(shè)置將過(guò)程中使用到的命令輸出到控制臺(tái)
                          this.ftpClient.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
                  }


                  /**
               * java編程中用于連接到FTP服務(wù)器
               * @param hostname 主機(jī)名
               * @param port 端口
               * @param username 用戶名
               * @param password 密碼
               * @return 是否連接成功
               * @throws IOException
               */
                   public boolean connect(String hostname,int port,String username,String password)
                           throws IOException {
                           //連接到FTP服務(wù)器
                           ftpClient.connect(hostname, port);
                           //如果采用默認(rèn)端口,可以使用ftp.connect(url)的方式直接連接FTP服務(wù)器
                           if(FTPReply.isPositiveCompletion(ftpClient.getReplyCode()))
                           {
                               
                                   if(ftpClient.login(username, password))
                                   {
                                            return true;
                               }
                           }
                         
                                    disconnect();
                                    return false;


                   }


                   /**
                    * 從FTP服務(wù)器上下載文件,支持?jǐn)帱c(diǎn)續(xù)傳功能
                    * @param remote 遠(yuǎn)程文件路徑
                    * @param local 本地文件路徑
                    * @param mode tb傳輸方式:PassiveMode方式,ActiveMode方式
                    * @return 是否成功
                    * @throws IOException
                    */
                   public DownloadStatus download(String remote,String local,String mode) throws IOException{


                                   //設(shè)置ftp傳輸方式
                                       if(mode.equalsIgnoreCase("P")){
                                               //PassiveMode傳輸
                                               ftpClient.enterLocalPassiveMode();
                                       }
                                       else {
                                               //ActiveMode傳輸
                                               ftpClient.enterLocalActiveMode();
                                       }
                   
                                       //設(shè)置以二進(jìn)制流的方式傳輸
                            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
                            
                            //下載狀態(tài)
                            DownloadStatus result;   
                            
                            //本地文件列表
                            File f = new File(local);
                            
                            //檢查遠(yuǎn)程文件是否存在   
                            FTPFile[] files = ftpClient.listFiles(new String(remote.getBytes("GBK"),"iso-8859-1"));   


                            if(files.length != 1){
                                System.out.println("遠(yuǎn)程文件不存在");   
                                return DownloadStatus.Remote_File_Noexist;   
                            }
                            
                            //獲得遠(yuǎn)端文件大小
                            long lRemoteSize = files[0].getSize();
                            
                            //構(gòu)建輸出對(duì)象
                        OutputStream ut = null ;
                        
                            //本地存在文件,進(jìn)行斷點(diǎn)下載 ;不存在則新下載
                            if(f.exists()){
                                    
                                    //構(gòu)建輸出對(duì)象
                                out = new FileOutputStream(f,true);
                                
                                //本地文件大小
                                long localSize = f.length();   


                                System.out.println("本地文件大小為:"+localSize);
                                
                                
                                //判定本地文件大小是否大于遠(yuǎn)程文件大小   
                                if(localSize >= lRemoteSize){
                                    System.out.println("本地文件大于遠(yuǎn)程文件,下載中止");   
                                    return DownloadStatus.Local_Bigger_Remote;   
                                }
                                
                                //否則進(jìn)行斷點(diǎn)續(xù)傳,并記錄狀態(tài)   
                                ftpClient.setRestartOffset(localSize);   
                                
                                InputStream in = ftpClient.retrieveFileStream(new String(remote.getBytes("GBK"),"iso-8859-1"));   
                                
                                byte[] bytes = new byte[1024];   
                                long step = lRemoteSize /100;  
                                
                                //存放下載進(jìn)度
                                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("下載進(jìn)度:"+process);   
                                        //TODO 更新文件下載進(jìn)度,值存放在process變量中   
                                    }   
                                }
                                //下載完成關(guān)閉輸入輸出流對(duì)象
                                in.close();   
                                out.close();   
                                boolean isDo = ftpClient.completePendingCommand();   
                                if(isDo){   
                                    result = DownloadStatus.Download_From_Break_Success;   
                                }else {   
                                    result = DownloadStatus.Download_From_Break_Failed;   
                                }   


                            }else {
                                    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("下載進(jìn)度:"+process);   
                                        //TODO 更新文件下載進(jìn)度,值存放在process變量中   
                                    }   
                                }   
                                in.close();   
                                out.close();   
                                boolean upNewStatus = ftpClient.completePendingCommand();   
                                if(upNewStatus){   
                                    result = DownloadStatus.Download_New_Success;   
                                }else {   
                                    result = DownloadStatus.Download_New_Failed;   
                                }   
                            }
                            return result;
                        }
                          
                        /**
                         * 上傳文件到FTP服務(wù)器,支持?jǐn)帱c(diǎn)續(xù)傳
                         * @param local 本地文件名稱,絕對(duì)路徑
                         * @param remote 遠(yuǎn)程文件路徑,使用/home/directory1/subdirectory/file.ext 按照Linux上的路徑指定方式,支持多級(jí)目錄嵌套,支持遞歸創(chuàng)建不存在的目錄結(jié)構(gòu)
                         * @param mode 傳輸方式:PassiveMode方式,ActiveMode方式
                         * @return 上傳結(jié)果
                         * @throws IOException
                         */
                        public UploadStatus upload(String local,String remote,String mode) throws IOException{
                            //設(shè)置PassiveMode傳輸
                            ftpClient.enterLocalPassiveMode();
                            //設(shè)置以二進(jìn)制流的方式傳輸
                            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
                            UploadStatus result;
                            //對(duì)遠(yuǎn)程目錄的處理
                            String remoteFileName = remote;
                            if(remote.contains("/")){
                                remoteFileName = remote.substring(remote.lastIndexOf("/")+1);
                                String directory = remote.substring(0,remote.lastIndexOf("/")+1);
                                if(!directory.equalsIgnoreCase("/")&&!ftpClient.changeWorkingDirectory(directory)){
                                    //如果遠(yuǎn)程目錄不存在,則遞歸創(chuàng)建遠(yuǎn)程服務(wù)器目錄
                                    int start=0;
                                    int end = 0;
                                    if(directory.startsWith("/")){
                                        start = 1;
                                    }else{
                                        start = 0;
                                    }
                                    end = directory.indexOf("/",start);
                                    while(true){
                                        String subDirectory = remote.substring(start,end);
                                        if(!ftpClient.changeWorkingDirectory(subDirectory)){
                                            if(ftpClient.makeDirectory(subDirectory)){
                                                ftpClient.changeWorkingDirectory(subDirectory);
                                            }else {
                                                System.out.println("創(chuàng)建目錄失敗");
                                                return UploadStatus.Create_Directory_Fail;
                                            }
                                        }
                                           
                                        start = end + 1;
                                        end = directory.indexOf("/",start);
                                           
                                        //檢查所有目錄是否創(chuàng)建完畢
                                        if(end <= start){
                                            break;
                                        }
                                    }
                                }
                            }
                               
                            //檢查遠(yuǎn)程是否存在文件
                            FTPFile[] files = ftpClient.listFiles(remoteFileName);
                            if(files.length == 1){
                                long remoteSize = files[0].getSize();
                                File f = new File(local);
                                long localSize = f.length();
                                if(remoteSize==localSize){
                                    return UploadStatus.File_Exits;
                                }else if(remoteSize > localSize){
                                    return UploadStatus.Remote_Bigger_Local;
                                }
                                   
                                //嘗試移動(dòng)文件內(nèi)讀取指針,實(shí)現(xiàn)斷點(diǎn)續(xù)傳
                                InputStream is = new FileInputStream(f);
                                if(is.skip(remoteSize)==remoteSize){
                                    ftpClient.setRestartOffset(remoteSize);
                                    if(ftpClient.storeFile(remote, is)){
                                        return UploadStatus.Upload_From_Break_Success;
                                    }
                                }
                                //如果斷點(diǎn)續(xù)傳沒(méi)有成功,則刪除服務(wù)器上文件,重新上傳
                                if(!ftpClient.deleteFile(remoteFileName)){
                                    return UploadStatus.Delete_Remote_Faild;
                                }
                                is = new FileInputStream(f);
                                if(ftpClient.storeFile(remote, is)){     
                                    result = UploadStatus.Upload_New_File_Success;
                                }else{
                                    result = UploadStatus.Upload_New_File_Failed;
                                }
                                is.close();
                            }else {
                                InputStream is = new FileInputStream(local);
                                if(ftpClient.storeFile(remoteFileName, is)){
                                    result = UploadStatus.Upload_New_File_Success;
                                }else{
                                    result = UploadStatus.Upload_New_File_Failed;
                                }
                                is.close();
                            }
                            return result;
                        }
                   
               /**
                * 斷開與遠(yuǎn)程服務(wù)器的連接
                * @throws IOException
                */
               public void disconnect() throws IOException{
                   if(ftpClient.isConnected()){
                       ftpClient.disconnect();
                   }
               }

          posted on 2012-07-25 15:29 chen11-1 閱讀(2220) 評(píng)論(3)  編輯  收藏

          Feedback

          # re: 文件FTP上傳支持?jǐn)帱c(diǎn)續(xù)傳demo 2013-04-08 16:27 dfsafd

          fsdfsdfsdf  回復(fù)  更多評(píng)論   

          # re: 文件FTP上傳支持?jǐn)帱c(diǎn)續(xù)傳demo 2013-04-08 16:27 dfsafd

          你好啊啊啊啊啊啊啊啊啊   回復(fù)  更多評(píng)論   

          # re: 文件FTP上傳支持?jǐn)帱c(diǎn)續(xù)傳demo 2013-09-11 13:56 揚(yáng)沙策馬

          有沒(méi)有全部代碼啊 我急需  回復(fù)  更多評(píng)論   


          只有注冊(cè)用戶登錄后才能發(fā)表評(píng)論。


          網(wǎng)站導(dǎo)航:
           
          主站蜘蛛池模板: 达日县| 江安县| 普洱| 梅河口市| 西畴县| 长治市| 正安县| 民丰县| 漠河县| 常德市| 长岛县| 永嘉县| 如皋市| 忻州市| 子长县| 博白县| 东阳市| 准格尔旗| 崇信县| 惠来县| 绩溪县| 冀州市| 潮安县| 桓仁| 竹山县| 务川| 昆山市| 海南省| 博客| 调兵山市| 元阳县| 镇原县| 沧州市| 濮阳市| 海丰县| 沙洋县| 枣庄市| 三明市| 海城市| 马鞍山市| 泰顺县|