Download files using Apache common ftp in Android

Source: Internet
Author: User

In Android using FTP download resources can use the ftp4j component, also can use Apache common net inside of the FTP component, these 2 components I have used.

Personal feeling Apache common net components are more useful, here is an example.

The use of FTP is encapsulated in the project, and the callback function has been added to the method of the continuation of the breakpoint.

Ftpcfg is used to store information such as FTP address, password, etc.

Ftpclientproxy is just a proxy, which mainly encapsulates the common FTP API


Iretrievelistener called, such as whether to download complete, whether there are errors, etc. can be notified to the UI layer

Ftpmanager calling the main portal

/** * buffersize default is 1024*4 *  * @author Gaofeng * 2014-6-18  */public class Ftpcfg {public ftpcfg () {}public int port;public int buffersize = 1024x768 * 4;public string Address;public string User;public string pass;}


/** * */package com.birds.mobile.net.ftp;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 android.util.log;/** * @author Gaofeng 2014-6-18 */public class Ftpclientproxy {ftpclient ftpclient = new FtpClient (); Ftpcfg config;protected ftpclientproxy (ftpcfg cfg) {this.config = cfg;} Public Ftpcfg GetConfig () {return config;} public Boolean connect () {try {ftpclientconfig ftpclientconfig = new Ftpclientconfig (Ftpclientconfig.syst_unix); Ftpclientconfig.setlenientfuturedates (True); Ftpclient.configure (ftpclientconfig); Ftpclient.connect ( Config.address, config.port); int reply = This.ftpClient.getReplyCode (); Ftpreply.ispositivecompletion (Reply)) {return false;} return true;} catch (SocketException e) {e.printstacktrace ();} catch (Ioexception e) {e.printstacktrace ();} return false;} public Boolean login () {if (!ftpclient.isconnected ()) {return false;} try {Boolean b = Ftpclient.login (Config.user, Config.pass); if (!b) {return false;} Ftpclient.setfiletype (ftpclient.file_structure); Ftpclient.enterlocalpassivemode (); Very Important//ftpclient.enterlocalactivemode ();//ftpclient.enterremotepassivemode ();// Ftpclient.enterremoteactivemode (Inetaddress.getbyname (config.address), config.port);  Ftpclient.setfiletype (Ftp.binary_file_type); return b;} catch (IOException e) {e.printstacktrace ();} return false;} Public ftpfile[] Getftpfiles (String remotedir) {try {return ftpclient.listfiles (remotedir);} catch (IOException e) { E.printstacktrace ();} return null;} Public Ftpfile getftpfile (String remotepath) {try {log.d ("", "Getftpfile ...)" + RemotePath); Ftpfile f = ftpclient.mlistfile (RemotePath); return f;} catch (IOException e) {e.printstacktrace ();} LOG.D ("", "getftpfile null ..."); return null;} Public InputStream GetremotefilestReam (String remotepath) {InputStream ios;try {iOS = Ftpclient.retrievefilestream (RemotePath); return iOS;} catch ( IOException e) {e.printstacktrace ();} return null;} public void Close () {if (ftpclient.isconnected ()) {try {ftpclient.logout ();} catch (IOException e) {e.printstacktrace ();} }try {ftpclient.disconnect ();} catch (IOException e) {e.printstacktrace ()}} public void Setrestartoffset (Long len) {ftpclient.setrestartoffset (len);//Breakpoint Continuation Position}public Boolean isDone () {try { return Ftpclient.completependingcommand ();} catch (IOException e) {e.printstacktrace ();} return false;}}


FTP has a variety of modes, this place is prone to error, resulting in unable to obtain the resources above the FTP.

Localpassivemode,localactivemode
is active mode and passive mode

To set up according to the network of the FTP server, you need to test it yourself.

/** * */package com.birds.mobile.net.ftp;import java.io.file;import Java.io.filenotfoundexception;import Java.io.fileoutputstream;import Java.io.ioexception;import Java.io.inputstream;import Java.io.OutputStream;import Org.apache.commons.net.ftp.ftpfile;import android.util.log;/** * @author Gaofeng 2014-6-18 */public class FTPManager { Ftpclientproxy Ftpproxy;iretrievelistener listener;volatile Boolean islogin = false;volatile Boolean stopDownload = False;protected Ftpmanager () {}public ftpmanager (ftpcfg cfg) {ftpproxy = new ftpclientproxy (CFG);} /** * Track listener for FTP downloading * @param listener */public void Setlistener (Iretrievelistener listener) {This.lis Tener = listener;} /** * Stop Download Task if you set true * @param stopdownload */public void Setstopdownload (Boolean stopdownload) {THIS.S Topdownload = Stopdownload;} Public ftpfile[] Showlistfile (String remotedir) {return ftpproxy.getftpfiles (remotedir);} public Boolean Connectlogin () {Boolean ok = false;if (ftpproxy.connect()) {OK = Ftpproxy.login ();} IsLogin = Ok;return OK;} /** * * @param remotedir of FTP * @param name of the file name under FTP Server ' s remote DIR. * @return Ftpfile */public FTPF Ile Getfilebyname (String remotedir, string name) {ftpfile[] files = showlistfile (Remotedir); if (Files! = null) {for (FTPFI Le F:Files) {if (Name.equalsignorecase (F.getname ())) {return F;}}} return null;} public void Download (string remotepath, String localPath, long offset) {listener.onstart (); File F = new file (LocalPath); byte[] buffer = new Byte[ftpproxy.getconfig (). Buffersize];int len = -1;long now = -1;boolean Append = False;inputstream ins = Null;outputstream ous = null;try {if (offset > 0) {//For continuation ftpproxy.setrestartoffset (of Fset); now = Offset;append = true;} LOG.D ("", "DownloadFile:" + Now + ";" + remotepath); ins = Ftpproxy.getremotefilestream (remotepath); ous = new Fileoutputstr EAM (f, append); LOG.D ("", "Downloadfilerenew:" + ins), while (len = ins.read (buffer))! =-1) {if (stopdownload) {break;} Ous.write (bufFer, 0, len), now = current + Len;listener.ontrack, or//monitors how many bytes are currently downloaded and can be used to display to the UI progress bar}if (stopdownload) {listener.oncancel ("") ;} else {if (Ftpproxy.isdone ()) {Listener.ondone ();} else {listener.onerror ("File Download error", error. File_download_error);}}} catch (IOException e) {e.printstacktrace (); Listener.onerror ("File Download Error:" + E, error. File_download_error);} Finally {try {ous.close (); Ins.close ()} catch (Exception E2) {}}}public void Download (string remotepath, String LocalPath ) {Download (RemotePath, LocalPath,-1);} public void Close () {ftpproxy.close ();} public static class Error {//self-defined error code public static final int file_no_fount = 9001;public static final int File_downloa D_error = 9002;public static final int login_error = 9003;public static final int connect_error = 9004;}}


callback function

Public interface Iretrievelistener {public void OnStart ();p ublic void Ontrack (Long nowoffset);p ublic void OnError (Object obj, int type);p ublic void OnCancel (Object obj);p ublic void Ondone ();}


The library uses Apache common Net 3.3.

The test code is placed in the attachment, not very perfect, but basic can be used.

http://download.csdn.net/detail/birdsaction/7580539

Related Article

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.