[Android Intermediate] using COMMONS-NET-FTP to implement FTP upload, download function

Source: Internet
Author: User
Tags gettext ftp client file transfer protocol filezilla ftp protocol

This article belongs to the study to share, if has the similarity purely coincidence

Use your spare time. Learn some practical things, assuming the hand is a little bit cheap. It's better to knock yourself out.

It is possible to complete various functions on Android with its own FTP component. This time is because the project sees uses the COMMONS-NET-FTP the package complete, therefore tries hackers with this.

First of all, there are some references in the code: Android using Apache common ftp to download files blog

This is the ability to share downloads and uploads of files using the FTP protocol (File Transfer Protocol) on Android. We can first understand thatFTP and HTTP are widely used protocols on the Internet. Used to transfer files between two computers.

Compared to HTTP. The FTP protocol is much more complex. The reason for this is that the FTP protocol uses two TCP connections, one is a command link to pass commands between FtpClient and server, and the other is a data link for uploading or downloading data.

1. To test the FTP service. This article uses the FileZilla server program to simulate.

https://filezilla-project.org/here does not say how to install, simple is to set the IP and user rights and so on.


2.demo structure, as always, within the red box is the focus. Jar package can be downloaded on Apache (http://commons.apache.org/proper/commons-net/download_net.cgi)


3. Main interface and source code



Mainactivity.java (the code is very rough, but let's see it)

/** * FTP Demo main interface * @author Jan * */public class Mainactivity extends Activity implements Onclicklistener {private static Final String TAG = "mainactivity";p rivate static final int show_dialog = 1000;private static final int hide_dialog = 1001 ;p rivate button mloginbutton;private EditText museret;private EditText mpasswordet;private button mdownloadbtn;private Button muploadbtn;private ftpmanager mftpmanager;private inputmethodmanager mimm;private ProgressDialog  Mprogressdialog;private Handler Mhandler = new Handler () {@Overridepublic void Handlemessage (Message msg) {if (Msg.what = = Show_dialog) {Showprogressdialog (msg.obj = = null?)

"Please wait ...": msg.obj.toString ());} else if (msg.what = = Hide_dialog) {hideprogressdialog ();}}}; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Requestwindowfeature (Window.feature_no_title); GetWindow (). SetFlags (WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); Setcontentview (r.layout.main); Mimm = (Inputmethodmanager) Getsystemservice (Context.input_method_service); Initview (); Ftpconfig config = new Ftpconfig ("192.168.1.29"), Config.user = "Jan"; config.pwd = "123456"; Museret.settext ( Config.user); Mpasswordet.settext (config.pwd); mftpmanager = ftpmanager.getinstance (config);} private void Initview () {Mloginbutton = (Button) Findviewbyid (R.id.login_button); Mloginbutton.setonclicklistener ( this); Museret = (EditText) Findviewbyid (r.id.username_et); Mpasswordet = (EditText) Findviewbyid (R.id.password_et); mdownloadbtn = (Button) Findviewbyid (R.id.button1); Mdownloadbtn.setonclicklistener (this); muploadbtn = (Button)Findviewbyid (R.id.button2); Muploadbtn.setonclicklistener (this);} private void Showprogressdialog (String content) {if (Mprogressdialog = = null) {Mprogressdialog = new ProgressDialog (This, Progressdialog.style_horizontal);} Mprogressdialog.settitle ("hint message"); Mprogressdialog.setmessage (content); mprogressdialog.setcancelable (false); Mprogressdialog.show ();} private void Hideprogressdialog () {if (Mprogressdialog! = null) {Mprogressdialog.dismiss ();}} @Overrideprotected void OnDestroy () {Super.ondestroy (); new Thread () {@Overridepublic void run () {mftpmanager.close ();}}. Start (); Toastutil.cancel ();} @Overridepublic void OnClick (View v) {switch (V.getid ()) {//Connection and login test case r.id.login_button:loginftp (); break;// Download the specified file on FTP case r.id.button1:downloadfile (); break;//upload the specified file on Android to Ftpservercase R.id.button2:uoloadfile (); Break;}} /** * Login function Test */private void Loginftp () {Mimm.hidesoftinputfromwindow (Mpasswordet.getwindowtoken (), 0); if ( Stringutils.isempty (Museret.gettext (). toString (). Trim ())) {Toastutil.showshOrttoast (This, "account cannot be empty"); return;} if (Stringutils.isempty (Mpasswordet.gettext (). toString (). Trim ())) {Toastutil.showshorttoast (this, "Password cannot be empty"); return;} New Thread () {@Overridepublic void run () {LOG.D (TAG, "Start login!"); if (Mftpmanager.connectftpserver ()) {LOG.D (TAG, "connectftpserver = true");//View files on remote FTP ftpfile[] files = Mftpmanager.getftpfiles (); LOG.I (Tag, "files.size=" +files.length); for (Ftpfile f:files) {LOG.I (tag, "File:" +f.getname ());} Toastutil.showshorttoast (Mainactivity.this, "Connection FTP succeeded", true);} ELSE{LOG.D (TAG, "connectftpserver = false");}}. Start ();} /** * Get a folder where files are downloaded * @return */public String getsdpath () {File Sddir = Null;boolean sdcardexist = Environment.getexterna Lstoragestate (). Equals (Android.os.Environment.MEDIA_MOUNTED); Infer if the SD card exists if (sdcardexist) {sddir = Environment.getexternalstoragedirectory ();//Get with folder}return sddir.tostring ();} /** * Download function test */private void DownloadFile () {new Thread () {@Overridepublic void run () {String LocalPath = Getsdpath (); if ( ! Stringutils.isEmpty (LocalPath)) {LocalPath = LocalPath + "/ftp_demo.log";} else {localPath = Getapplicationcontext (). Getfilesdir (). GetAbsolutePath () + "/ftp_demo.log";} LOG.D (TAG, "localpath=" + LocalPath); Mftpmanager.setretrievelistener (new Iretrievelistener () {@Overridepublic void Ontrack (Long CurPos) {LOG.D (TAG, "--ontrack--" + CurPos);} @Overridepublic void OnStart () {LOG.D (TAG, "--onstart--"); Mhandler.sendemptymessage (Show_dialog);} @Overridepublic void OnError (int code, String msg) {LOG.E (TAG, "Download error:" + msg); Mhandler.sendemptymessage (Hide_ DIALOG); Toastutil.showshorttoast (Getapplicationcontext (), "Download Failed", true); @Overridepublic void Ondone () {log.i (TAG, "download Success"); Mhandler.sendemptymessage (Hide_dialog); Toastutil.showshorttoast (mainactivity.this, "Download succeeded", true);} @Overridepublic void OnCancel () {log.i (TAG, "Download OnCancel"); Mhandler.sendemptymessage (Hide_dialog);}}); Mftpmanager.downloadfile ("/ftp_test.log", LocalPath);}}. Start ();} /** * Upload operation */private void Uoloadfile () {New Thread (nEW Runnable () {@Overridepublic void run () {String LocalPath = Getsdpath (); Stringutils.isempty (LocalPath)) {LocalPath = LocalPath + "/ftp_demo.log";} else {localPath = Getapplicationcontext (). Getfilesdir (). GetAbsolutePath () + "/ftp_demo.log";} LOG.D (TAG, "localpath=" + LocalPath); File File = new file (LocalPath); try {if (!file.exists ()) {file.createnewfile ();} FileOutputStream fos = new FileOutputStream (file, false); BufferedWriter bw = new BufferedWriter (new OutputStreamWriter (FOS, "utf-8"); Bw.write ("FTP Upload test Example"); Bw.flush (); Bw.close ();} catch (IOException e) {e.printstacktrace ();} Mftpmanager.setretrievelistener (New Iretrievelistener () {@Overridepublic void Ontrack (Long CurPos) {LOG.D (TAG, " upload--ontrack--"+ CurPos);} @Overridepublic void OnStart () {LOG.D (TAG, "upload--onstart--"); Message msg = Mhandler.obtainmessage (show_dialog); msg.obj = "uploading ..."; mhandler.sendmessage (msg); @Overridepublic void OnError (int code, String msg) {LOG.E (TAG, "Upload error:" + msg); Mhandler.sendemptymessaGE (Hide_dialog); Toastutil.showshorttoast (Mainactivity.this, "Upload failed", true);} @Overridepublic void Ondone () {log.i (TAG, "upload success"); Mhandler.sendemptymessage (Hide_dialog); Toastutil.showshorttoast (Mainactivity.this, "Upload succeeded", true);} @Overridepublic void OnCancel () {log.i (TAG, "Upload onCancel"); Mhandler.sendemptymessage (Hide_dialog);}}); Mftpmanager.uploadfile (LocalPath, "Ftp_up.log");}). Start ();}}



4.ftpmanager.java

Package Org.jan.ftp.utils;import Java.io.file;import Java.io.fileinputstream;import java.io.FileNotFoundException; Import Java.io.fileoutputstream;import Java.io.ioexception;import Java.io.inputstream;import Java.net.socketexception;import Org.apache.commons.net.ftp.ftp;import org.apache.commons.net.ftp.FTPClient; Import Org.apache.commons.net.ftp.ftpclientconfig;import Org.apache.commons.net.ftp.ftpfile;import Org.apache.commons.net.ftp.ftpreply;import Org.apache.commons.net.ftp.ftpsclient;import Org.apache.commons.net.util.trustmanagerutils;import Org.jan.ftp.demo.bean.ftpconfig;import android.util.Log;/** * FTP Client Management class * * @author Jan */public class Ftpmanager {private static final String TAG = "Ftpmanager";p rivate static Ftpmanager mftpmanager;private ftpclient mftpclient;private ftpsclient mftpsclient;private static FTPConfig mConfig; Private Iretrievelistener retrievelistener;private Boolean Isftps = false;volatile Boolean islogin = False;volatile Boole An isstopdownload = False;pRivate Ftpmanager () {mftpclient = new ftpclient (); mftpsclient = new Ftpsclient (false); Mftpsclient.settrustmanager ( Trustmanagerutils.getacceptalltrustmanager ());} public static Ftpmanager getinstance (Ftpconfig cfg) {if (Mftpmanager = = null) {Mftpmanager = new Ftpmanager ();} Mconfig = Cfg;return Mftpmanager;} public static Ftpmanager getinstance (String host, int port) {if (Mftpmanager = = null) {Mftpmanager = new Ftpmanager ();} Mconfig = new Ftpconfig (host, port); return Mftpmanager;} public void Setretrievelistener (Iretrievelistener retrievelistener) {this.retrievelistener = Retrievelistener;} /** * Connect and Login FTP Service * * @return */public boolean connectftpserver () {try {ftpclientconfig ftpclientcfg = new Ftpclientconfig (Ftpclientconfig.syst_unix); Ftpclientcfg.setlenientfuturedates (true); Mftpclient.configure (FTPCLIENTCFG); Mftpclient.setconnecttimeout (15000); Mftpclient.connect (mconfig.ipadress, mconfig.port); login (); int replyCode = Mftpclient.getreplycode (); if (! Ftpreply.ispositivecompletion (Replycode){mftpclient.disconnect (); return false;}} catch (SocketException e) {e.printstacktrace (); return false;} catch (IOException e) {e.printstacktrace (); return false;} return true;} /** * Login FTP Server * @return */public Boolean login () {try {if (mftpclient.isconnected ()) {Boolean islogin = Mftpclient.login ( Mconfig.user, mconfig.pwd); if (!islogin) {return false;} Mftpclient.setcontrolencoding ("GBK"); Mftpclient.setfiletype (ftpclient.file_structure); Mftpclient.enterlocalactivemode ();//Mftpclient.enterremotepassivemode ();//Mftpclient.enterremoteactivemode (// Inetaddress.getbyname (mconfig.ipadress), mconfig.port); Mftpclient.setfiletype (Ftp.binary_file_type); return isLogin;}} catch (IOException e) {e.printstacktrace ();} return false;} /** * Exit and close this connection */public void Close () {try {if (mftpclient.isconnected ()) {mftpclient.logout ()}; Mftpclient.disconnect ();} catch (IOException e) {e.printstacktrace ();}} /** * Download files on FTP * @param remotefilename * @param localfilename * @param currentsize */public void DownLoadFile (String remotefilename, String Localfilename,long currentsize) {log.i (TAG, "DownloadFile filename=" + Remotefilename + "currentsize=" + currentsize); if (retrievelistener! = null) {Retrievelistener.onstart ();} byte[] buffer = new Byte[mconfig.buffersize];int len = -1;long now = -1;boolean append = false;if (mftpclient! = null) {in Putstream ins = null; FileOutputStream fos = null;try {file LocalFile = new File (localfilename); if (CurrentSize > 0) {mftpclient.setrestartof Fset (currentsize); now = Currentsize;append = true;} INS = Getremotefilestream (remotefilename); fos = new FileOutputStream (LocalFile, append); if (ins = = null) {throw new Fileno Tfoundexception ("Remote file is not exist");} while (len = ins.read (buffer))! =-1) {if (isstopdownload) {break;} Fos.write (buffer, 0, Len); now + + len;retrievelistener.ontrack (now);} if (isstopdownload) {retrievelistener.oncancel ();} else {if (Mftpclient.completependingcommand ()) { Retrievelistener.ondone ();} else {retrievelistener.onerror (ERROR). DownlOad_error, "download Fail");}}} catch (FileNotFoundException e) {retrievelistener.onerror (ERROR. File_no_fount, "Download fail:" + e);} catch (IOException e) {retrievelistener.onerror (ERROR. Io_error, "Download fail:" + e);} Finally {try {ins.close (); Fos.close ()} catch (Exception E2) {}}}}/** * Download the specified file on Ftpserver to local * @param remotepath * @param LocalPath */public void DownLoadFile (String remotepath, String localPath) {downLoadFile (RemotePath, LocalPath,-1);} Private InputStream Getremotefilestream (String remotefilepath) {InputStream is = null;try {is = Mftpclient.retrievefilestream (Remotefilepath);} catch (IOException e) {e.printstacktrace ();} return is;}  /** * Upload file * @param localPath Local file path to upload (with suffix) * @param workdirectory upload ftpserver The specified file folder * @param desfilename target file name * @return */public boolean UploadFile (String LocalPath, String workdirectory,string desfilename) {log.i (TAG, "UploadFile l Ocalpath= "+ LocalPath +" desfilename= "+ desfilename); if (retrievelistener! = null) {RetrievelisteNer.onstart ();} try {if (mftpclient! = null && mftpclient.isconnected ()) {//Set storage path Mftpclient.makedirectory (workdirectory); Mftpclient.changeworkingdirectory (workdirectory); mftpclient.setbuffersize (1024); FileInputStream fis = new FileInputStream (LocalPath); Boolean isuploadsuccess = Mftpclient.storefile (Desfilename, FIS); if (isuploadsuccess) {if (Retrievelistener! = null) {Retrievelistener.ondone ();}} else {if (Retrievelistener! = null) {RET Rievelistener.onerror (ERROR. Upload_error, "UPLOAD fail");}} Fis.close (); return isuploadsuccess;}} catch (IOException e) {e.printstacktrace (); if (retrievelistener! = null) {Retrievelistener.onerror (ERROR. Io_error, "Upload ERROR:" + E);}} return false;} /** * Upload files to the destination FTP server root folder * * @param localfilename * source file to be uploaded * @param remotefilename * Server file name * @ Return upload Successful Identity */public boolean uploadfile (String localfilename, String remotefilename) {return UploadFile ( LocalFilename, "/", Remotefilename);} Public ftpfile[] Getftpfiles () {try{if (!mftpclient.isconnected ()) {return null;} Mftpclient.changetoparentdirectory (); return Mftpclient.listfiles ();} catch (IOException e) {e.printstacktrace ();} return null;} public boolean DeleteFile (String pathname) {try {return mftpclient.deletefile (pathname);} catch (IOException e) { E.printstacktrace ();} return false;} public boolean createdirectory (String pathname) {try {return mftpclient.makedirectory (pathname);} catch (IOException e) {E.printstacktrace ();} return false;} Public ftpfile[] Getftpfiles (String remotedir) {try {if (!mftpclient.isconnected ()) {return null;} Return Mftpclient.listfiles (Remotedir);} catch (IOException e) {e.printstacktrace ();} return null;} public Boolean isstopdownload () {return isstopdownload;} public void Setstopdownload (Boolean isstopdownload) {this.isstopdownload = Isstopdownload;} public Boolean Isftps () {return ISFTPS;} public void Setftps (Boolean Isftps) {if (Isftps) {mftpclient = mftpsclient;} else {mftpclient = new ftpclient ();} This.isftps = Isftps;} Public InterFace Iretrievelistener {public void OnStart ();p ublic void Ontrack (long curpos);p ublic void onError (int errorCode, String E rrormsg);p ublic void OnCancel ();p ublic void Ondone (); public static class ERROR {public static final int file_no_fount = 4000;public static final int file_download_error = 4001 ;p ublic static final int login_error = 4002;public static final int connect_error = 4003;public static final int io_error = 4004;public static final int download_error = 4005;public static final int upload_error = 4006;}}


It's actually very easy to use!

If you need a demo, please download it yourself.

Click here to download it.






[Android Intermediate] use Commons-net-ftp for FTP upload, download function

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.