Java implementation of multi-threaded breakpoint continuation, upload download

Source: Internet
Author: User
Tags create directory

Using Apache's Commons-net-ftp-ftpclient
Import Java.io.file;import java.io.fileoutputstream;import Java.io.ioexception;import Java.io.InputStream;import Java.io.outputstream;import Java.io.printwriter;import Java.io.randomaccessfile;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;import org.junit.test;/** *//*** FTP utility class with support for the continuation of breakpoints * @version 0.1 basic breakpoint upload Download * @version 0.2 implementation Upload Download progress report * @version 0.3 implementation of Chinese catalog creation and Chinese file creation, add support for Chinese */public class continuedftp{//enum class Uploadstatus code public enum Uploadstatus {create_directory_fail,//remote server corresponding directory creation failed create_directory_success,//remote server Pathbreaker directory succeeded Upload_new_file_ Success,//upload new file successfully upload_new_file_failed,//upload new file failed file_exits,//file already exists remote_bigger_local,//remote file is larger than local file Upload_ From_break_success,//Breakpoint continued success upload_from_break_failed,//breakpoint continued failure delete_remote_faild; Delete remote file failed}//enum class downloadstatus code public enum Downloadstatus {remote_file_noexist,//remote file does not exist LOCAl_bigger_remote,//local file larger than remote file download_from_break_success,//Breakpoint download file successfully download_from_break_failed,// Breakpoint Download file failed download_new_success,//New download file successfully download_new_failed; New download file failed}public ftpclient ftpclient = new FtpClient ();p rivate String ftpurl,username,pwd,ftpport,file1,file2;public ContinueFTP2 (String _ftpurl,string _username,string _pwd,string _ftpport,string _file1,string _file2) {// Set the commands used in the process to output to the console Ftpurl = _ftpurl;username = _username;pwd = _pwd;ftpport = _ftpport;file1 = _file1;file2 = _file2;this.f Tpclient.addprotocolcommandlistener (New Printcommandlistener (New PrintWriter (System.out))); /** *//*** Connect to FTP server * @param hostname hostname * @param port * @param username user name * @param password Password * @return Connection Successful * @throw S 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;} /** *//*** Download the file from the FTP server, support the continuation of the breakpoint, upload a percentage report * @param remote file path * @param local file path * @return Upload status * @throws ioexception*/pub Lic downloadstatus Download (String remote,string local) throws ioexception{//set passive mode Ftpclient.enterlocalpassivemode () ;//sets the Ftpclient.setfiletype (FTP) to be transferred in binary mode. Binary_file_type);D ownloadstatus result;//Check if the remote file exists ftpfile[] files = ftpclient.listfiles (New String ( Remote.getbytes ("GBK"), "iso-8859-1"), if (files.length! = 1) {System.out.println ("Remote file does not exist"); return Downloadstatus.remote_file_noexist;} Long lremotesize = Files[0].getsize (); File F = new file (local),//locally exists, a breakpoint is downloaded if (f.exists ()) {Long localsize = F.length ();//Determines whether the local file size is greater than the remote file size if (localsize >= lremotesize) {System.out.println ("local file is larger than remote file, download aborted"); return downloadstatus.local_bigger_remote;} Perform a breakpoint continuation and record the status fileoutputstream out = new FileOutputStream (f,true); Ftpclient.setrestartoffset (localsize); I Nputstream 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% = = 0) System.out.println ("Download Progress:" +process)//todo update file download progress, value stored in the process variable}}in.close (); O Ut.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/ste P;if (nowprocess > process) {process = nowprocess;if (process% = = 0) System.out.println ("Download Progress:" +process);//todo Under Update filesLoad progress, value is stored in the process variable}}in.close (); Out.close (); Boolean upnewstatus = Ftpclient.completependingcommand (); if ( Upnewstatus) {result = downloadstatus.download_new_success;} else {result = downloadstatus.download_new_failed;}} return result;} /** *//*** upload files to the FTP server, support the extension of the breakpoint * @param local file name, absolute path * @param remote file path remotely, using/home/directory1/subdirectory/ File.ext or Http://www.guihua.org/subdirectory/file.ext follow the path designation on Linux, support multi-level directory nesting, support recursive creation of nonexistent directory structure * @return upload results * @ Throws Ioexception*/public Uploadstatus upload (String local,string remote) throws ioexception{// Set the Passivemode transport Ftpclient.enterlocalpassivemode ();//Set the Ftpclient.setfiletype (FTP) to be transmitted in a binary stream mode. Binary_file_type); Ftpclient.setcontrolencoding ("GBK"); Uploadstatus result;//Processing of remote directories string remotefilename = Remote;if (Remote.contains ("/")) {Remotefilename = Remote.substring (Remote.lastindexof ("/") +1);//create server remote directory structure, create failure directly return if (Createdirecroty (remote, ftpclient) = = Uploadstatus.create_directory_fail) {return uploadstatus.create_directory_fail;}} Check if the remote exists file ftpfile[]Files = ftpclient.listfiles (new String (Remotefilename.getbytes ("GBK"), "iso-8859-1")); 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;} Attempt to move the pointer within the file to achieve a continuation of the breakpoint result = UploadFile (Remotefilename, F, ftpclient, remotesize);//If the breakpoint continuation is unsuccessful, delete the file on the server and re-upload if ( result = = uploadstatus.upload_from_break_failed) {if (!ftpclient.deletefile (Remotefilename)) {return Uploadstatus.delete_remote_faild;} result = UploadFile (Remotefilename, F, ftpclient, 0);}} else {result = UploadFile (Remotefilename, New File (local), ftpclient, 0);} return result;} /** *//*** disconnecting from the remote server * @throws ioexception*/public void disconnect () throws Ioexception{if (Ftpclient.isconnected ()) { Ftpclient.disconnect ();}} /** *//*** to create a remote server directory * @param remote server file absolute path * @param ftpclient ftpclient Object * @return Directory creation succeeded * @throws ioexception*/p Ublic 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")) {//If the remote directory does not exist, The remote server directory is created recursively 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 ("Failed to create directory"); return uploadstatus.create_directory_fail;}}  Start = end + 1;end = Directory.indexof ("/", start);//Check that all directories are created if (end<= Start) {break;}}} return status;} /** *//*** upload files to the server, new uploads and breakpoints continue * @param remotefile remote file name, the server working directory has been changed before uploading * @param localfile local file handle, absolute path * @param proc Essstep the processing progress step value that needs to be displayed * @param ftpclient ftpclient Reference * @return * @throws ioexception*/public uploadstatus uploadfile (String Remotefile,file localfile,ftpclient Ftpclient,long remotesize) throws Ioexception{uploadstatus status;//Show progress upload long Step= Localfile.length ()/100;long Process= 0;Long Localreadbytes= 0L;Randomaccessfile RAF= newRandomaccessfile (LocalFile, "R"); OutputStream out= Ftpclient.appendfilestream (NewString (remotefile.getbytes ("GBK"), "iso-8859-1"));//breakpoint Continuation if (Remotesize>0) {Ftpclient.setrestartoffset (remotesize);p rocess = 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 ("Upload progress:" + process),//todo report upload status}}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;}}
View Code

Java implementation of multi-threaded breakpoint continuation, upload download

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.