tbwshc

          文件FTP上傳支持斷點續傳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實現
          * 創建日期: 2012-5-21
          * 創建地址: 西安
          * 作者:  Eric.Hao
          **************************************************************/
          public class ContinueFTP {
                 
                  private FTPClient ftpClient = new FTPClient();
                 
                  public ContinueFTP(){
                         
                          //設置將過程中使用到的命令輸出到控制臺
                          this.ftpClient.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
                  }


                  /**
               * java編程中用于連接到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 {
                           //連接到FTP服務器
                           ftpClient.connect(hostname, port);
                           //如果采用默認端口,可以使用ftp.connect(url)的方式直接連接FTP服務器
                           if(FTPReply.isPositiveCompletion(ftpClient.getReplyCode()))
                           {
                               
                                   if(ftpClient.login(username, password))
                                   {
                                            return true;
                               }
                           }
                         
                                    disconnect();
                                    return false;


                   }


                   /**
                    * 從FTP服務器上下載文件,支持斷點續傳功能
                    * @param remote 遠程文件路徑
                    * @param local 本地文件路徑
                    * @param mode tb傳輸方式:PassiveMode方式,ActiveMode方式
                    * @return 是否成功
                    * @throws IOException
                    */
                   public DownloadStatus download(String remote,String local,String mode) throws IOException{


                                   //設置ftp傳輸方式
                                       if(mode.equalsIgnoreCase("P")){
                                               //PassiveMode傳輸
                                               ftpClient.enterLocalPassiveMode();
                                       }
                                       else {
                                               //ActiveMode傳輸
                                               ftpClient.enterLocalActiveMode();
                                       }
                   
                                       //設置以二進制流的方式傳輸
                            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
                            
                            //下載狀態
                            DownloadStatus result;   
                            
                            //本地文件列表
                            File f = new File(local);
                            
                            //檢查遠程文件是否存在   
                            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();
                            
                            //構建輸出對象
                        OutputStream ut = null ;
                        
                            //本地存在文件,進行斷點下載 ;不存在則新下載
                            if(f.exists()){
                                    
                                    //構建輸出對象
                                out = new FileOutputStream(f,true);
                                
                                //本地文件大小
                                long localSize = f.length();   


                                System.out.println("本地文件大小為:"+localSize);
                                
                                
                                //判定本地文件大小是否大于遠程文件大小   
                                if(localSize >= lRemoteSize){
                                    System.out.println("本地文件大于遠程文件,下載中止");   
                                    return DownloadStatus.Local_Bigger_Remote;   
                                }
                                
                                //否則進行斷點續傳,并記錄狀態   
                                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 {
                                    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;
                        }
                          
                        /**
                         * 上傳文件到FTP服務器,支持斷點續傳
                         * @param local 本地文件名稱,絕對路徑
                         * @param remote 遠程文件路徑,使用/home/directory1/subdirectory/file.ext 按照Linux上的路徑指定方式,支持多級目錄嵌套,支持遞歸創建不存在的目錄結構
                         * @param mode 傳輸方式:PassiveMode方式,ActiveMode方式
                         * @return 上傳結果
                         * @throws IOException
                         */
                        public UploadStatus upload(String local,String remote,String mode) throws IOException{
                            //設置PassiveMode傳輸
                            ftpClient.enterLocalPassiveMode();
                            //設置以二進制流的方式傳輸
                            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
                            UploadStatus result;
                            //對遠程目錄的處理
                            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)){
                                    //如果遠程目錄不存在,則遞歸創建遠程服務器目錄
                                    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("創建目錄失敗");
                                                return UploadStatus.Create_Directory_Fail;
                                            }
                                        }
                                           
                                        start = end + 1;
                                        end = directory.indexOf("/",start);
                                           
                                        //檢查所有目錄是否創建完畢
                                        if(end <= start){
                                            break;
                                        }
                                    }
                                }
                            }
                               
                            //檢查遠程是否存在文件
                            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;
                                }
                                   
                                //嘗試移動文件內讀取指針,實現斷點續傳
                                InputStream is = new FileInputStream(f);
                                if(is.skip(remoteSize)==remoteSize){
                                    ftpClient.setRestartOffset(remoteSize);
                                    if(ftpClient.storeFile(remote, is)){
                                        return UploadStatus.Upload_From_Break_Success;
                                    }
                                }
                                //如果斷點續傳沒有成功,則刪除服務器上文件,重新上傳
                                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;
                        }
                   
               /**
                * 斷開與遠程服務器的連接
                * @throws IOException
                */
               public void disconnect() throws IOException{
                   if(ftpClient.isConnected()){
                       ftpClient.disconnect();
                   }
               }

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

          Feedback

          # re: 文件FTP上傳支持斷點續傳demo 2013-04-08 16:27 dfsafd

          fsdfsdfsdf  回復  更多評論   

          # re: 文件FTP上傳支持斷點續傳demo 2013-04-08 16:27 dfsafd

          你好啊啊啊啊啊啊啊啊啊   回復  更多評論   

          # re: 文件FTP上傳支持斷點續傳demo 2013-09-11 13:56 揚沙策馬

          有沒有全部代碼啊 我急需  回復  更多評論   


          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          主站蜘蛛池模板: 吉水县| 桂东县| 汽车| 昆山市| 河南省| 天等县| 休宁县| 乐业县| 双城市| 肃南| 利津县| 青神县| 临漳县| 铅山县| 永丰县| 安丘市| 古田县| 苍南县| 内丘县| 工布江达县| 门源| 衡山县| 金乡县| 滁州市| 白银市| 德保县| 浑源县| 毕节市| 新乡县| 托克托县| 张掖市| 清徐县| 建德市| 佛冈县| 洛浦县| 东海县| 平阳县| 惠安县| 始兴县| 开阳县| 富源县|