Android uses FTP upload, download, contains progress.
The code section is mainly divided into three files: Mainactivity,ftp,progressinputstream
1. mainactivity
Package com.ftp;
Import Java.io.File;
Import java.io.IOException;
Import java.util.LinkedList;
Import Com.ftp.FTP.DeleteFileProgressListener;
Import Com.ftp.FTP.DownLoadProgressListener;
Import Com.ftp.FTP.UploadProgressListener;
Import android.app.Activity;
Import Android.os.Bundle;
Import Android.os.Message;
Import Android.util.Log;
Import Android.view.View;
Import Android.view.View.OnClickListener;
Import Android.widget.Button;
Import Android.widget.EditText;
Import Android.widget.Toast;
public class Mainactivity extends activity {private static final String TAG = "mainactivity";
public static final String ftp_connect_successs = "FTP connection succeeded";
public static final String ftp_connect_fail = "FTP connection Failed";
public static final String ftp_disconnect_success = "FTP disconnected";
public static final String ftp_file_notexists = "file does not exist on FTP";
public static final String ftp_upload_success = "FTP file upload succeeded"; public static final String ftp_upload_fail = "FTP textPiece upload Failed ";
public static final String ftp_upload_loading = "FTP file is uploading";
public static final String ftp_down_loading = "FTP file is downloading";
public static final String ftp_down_success = "FTP file download succeeded";
public static final String ftp_down_fail = "FTP file download Failed";
public static final String ftp_deletefile_success = "FTP file deletion succeeded";
public static final String ftp_deletefile_fail = "FTP file deletion failed";
@Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
Setcontentview (R.layout.main);
Initview (); private void Initview () {//Upload function//new ftp (). Uploadmultifile Upload//new FTP () for multiple files. Uploadsinglefil
E for single file upload Button buttonupload = (button) Findviewbyid (r.id.button_upload);
Buttonupload.setonclicklistener (New Onclicklistener () {@Override public void OnClick (View v) {
New Thread (New Runnable () {@Override public void run () {
Upload file File = new file ("/mnt/sdcard/ftptest.docx"); try {///single File Upload new FTP (). Uploadsinglefile (File, "/fff", New Uploadprogre Sslistener () {@Override public void onuploadprogress (String currentstep,long Uploa
Dsize,file File) {//TODO auto-generated Method Stub log.d (TAG, currentstep); if (Currentstep.equals (mainactivity.ftp_upload_success)) {Lo
G.D (TAG, "-----shanchuan--successful");
else if (currentstep.equals (mainactivity.ftp_upload_loading)) {Long fize = File.length ();
float num = (float) uploadsize/(float) fize;
int result = (int) (NUM * 100);
LOG.D (TAG, "-----Shangchuan---" +result + "%");
} }
});
catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();
}}). Start ();
}
});
Download feature button Buttondown = (button) Findviewbyid (R.id.button_down);
Buttondown.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) {
New Thread (New Runnable () {@Override public void run () { Download the try {//Single file download new FTP (). Downloadsinglefile ("/fff/ftp
Test.docx ","/mnt/sdcard/download/"," Ftptest.docx ", new Downloadprogresslistener () {@Override public void Ondownloadprogress (String currentstep, long downprocess, file file) {log.d (TAG, Curr ENTSTEP);
if (Currentstep.equals (mainactivity.ftp_down_success)) {LOG.D (TAG, "-----xiaza
I--successful "); else if (currentstep.equals (mainactivity.ftp_down_loading)) {log.d TAG, "-----Xiazai---" +downprocess
+ "%");
}
}
});
catch (Exception e) {//TODO auto-generated catch block E.printstacktrace ();
}}). Start ();
}
});
Delete Feature button Buttondelete = (button) Findviewbyid (R.id.button_delete);
Buttondelete.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) {
New Thread (New Runnable () {@Override public void run () { Delete try {new FTP (). Deletesinglefile ("/fff/ftptest.docx", new Deletefileprogresslistener () {@Override Publ
IC void ondeleteprogress (String currentstep) {log.d (TAG, currentstep); if (Currentstep.equals (mainactivity.ftp_deletefile_success)) {LOG.D (TAG, "-----shanchu--succe
SS ");
else if (currentstep.equals (Mainactivity.ftp_deletefile_fail)) {LOG.D (TAG, "-----shanchu--fail");
}
}
});
catch (Exception e) {//TODO auto-generated catch block E.printstacktrace ();
}}). Start ();
}
});
}
}
2. FTP
Package com.ftp;
Import Java.io.BufferedInputStream;
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.util.Date;
Import java.util.LinkedList;
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;
public class FTP {/** * server name.
* * Private String hostName;
/** * Port number * * Private int serverport;
/** * User name.
* * Private String userName;
/** * password.
* * Private String password;
/** * FTP connection.
* * Private ftpclient ftpclient;
Public FTP () {this.hostname = "192.168.1.101";
This.serverport = 21;
This.username = "admin";
This.password = "1234";
This.ftpclient = new FtpClient (); }
// -------------------------------------------------------File Upload Method------------------------------------------------/** * Upload a single file.
* * @param localfile * Local file * @param remotepath * FTP directory * @param listener * listener * @throws IOException */public void Uploadsinglefile (File singlefile, String RemotePath, Uploadprogresslis
Tener listener) throws IOException {//upload before initialization this.uploadbeforeoperate (RemotePath, listener);
Boolean flag;
Flag = Uploadingsingle (singlefile, listener);
if (flag) {listener.onuploadprogress (mainactivity.ftp_upload_success, 0, Singlefile);
else {listener.onuploadprogress (mainactivity.ftp_upload_fail, 0, Singlefile);
After the upload is completed, close the connection this.uploadafteroperate (listener);
/** * Upload multiple files.
* * @param localfile * Local file * @param remotepath * FTP directory * @param listener * listener
* @throws IOException * *public void Uploadmultifile (linkedlist<file> filelist, String RemotePath, Uploadprogresslistener listener) th
Rows IOException {//upload before initialization this.uploadbeforeoperate (RemotePath, listener);
Boolean flag;
for (File singlefile:filelist) {flag = Uploadingsingle (singlefile, listener);
if (flag) {listener.onuploadprogress (mainactivity.ftp_upload_success, 0, Singlefile);
else {listener.onuploadprogress (mainactivity.ftp_upload_fail, 0, Singlefile);
After the upload is completed, close the connection this.uploadafteroperate (listener);
/** * Upload a single file. * * @param localfile * Local file * @return True upload success, false upload failed * @throws IOException/Private Boo Lean Uploadingsingle (File localfile, Uploadprogresslistener listener) throws IOException {Boolean flag = True
; No progress////Create input stream//InputStream InputStream = new FileInputStream (locaLfile);
Upload a single file//flag = Ftpclient.storefile (Localfile.getname (), InputStream);
Close file stream//Inputstream.close ();
The method with progress bufferedinputstream Buffin = new Bufferedinputstream (new FileInputStream (LocalFile));
Progressinputstream progressinput = new Progressinputstream (Buffin, Listener, LocalFile);
Flag = Ftpclient.storefile (Localfile.getname (), progressinput);
Buffin.close ();
return flag; /** * Initialize relevant parameters before uploading files * * @param remotepath * FTP directory * @param listener * listener * @throws IOException */private void Uploadbeforeoperate (String remotepath, Uploadprogresslistener Listener)
Throws IOException {//Open FTP service try {this.openconnect ();
Listener.onuploadprogress (mainactivity.ftp_connect_successs, 0, NULL);
catch (IOException E1) {e1.printstacktrace (); Listener.onuploadprogress (mainactivity.ftp_Connect_fail, 0, NULL);
Return
}//Set mode Ftpclient.setfiletransfermode (Org.apache.commons.net.ftp.FTP.STREAM_TRANSFER_MODE);
Create folders under FTP Ftpclient.makedirectory (RemotePath);
Change FTP directory Ftpclient.changeworkingdirectory (RemotePath); Upload a single file}/** * Close the connection after the upload * * * @param listener * @throws IOException/private void up
Loadafteroperate (Uploadprogresslistener listener) throws IOException {This.closeconnect ();
Listener.onuploadprogress (mainactivity.ftp_disconnect_success, 0, NULL);
//-------------------------------------------------------File Download method------------------------------------------------
/** * Download a single file to achieve a breakpoint download. * * @param serverpath * FTP directory and file path * @param localpath * Local directory * @param fileName * File name after download * @param listener * listener * @throws ioexception/public void Downloadsinglefile (String Serverpath,String LocalPath, String fileName, Downloadprogresslistener listener) throws Exception {//Open FTP service try
{This.openconnect ();
Listener.ondownloadprogress (mainactivity.ftp_connect_successs, 0, NULL);
catch (IOException E1) {e1.printstacktrace ();
Listener.ondownloadprogress (mainactivity.ftp_connect_fail, 0, NULL);
Return
///First determine if the server file exists ftpfile[] files = ftpclient.listfiles (Serverpath);
if (Files.length = = 0) {listener.ondownloadprogress (mainactivity.ftp_file_notexists, 0, NULL);
Return
//Create local folder File Mkfile = new file (LocalPath);
if (!mkfile.exists ()) {mkfile.mkdirs ();
} localpath = LocalPath + fileName; Then determine whether the downloaded file can be breakpoint download long serversize = Files[0].getsize ();
Gets the length of the remote file, file LocalFile = new file (LocalPath);
Long localsize = 0;
if (localfile.exists ()) {localsize = Localfile.length ();//If the local file exists, get the length of the local file if (localsize >= serversize) {File File = new file (LocalPath);
File.delete ();
}//Progress long step = serversize/100;
Long process = 0;
Long currentsize = 0;
Start preparing to download the file OutputStream out = new FileOutputStream (LocalFile, true);
Ftpclient.setrestartoffset (localsize);
InputStream input = Ftpclient.retrievefilestream (Serverpath);
Byte[] B = new byte[1024];
int length = 0;
while (length = Input.read (b))!=-1) {out.write (b, 0, length);
CurrentSize = currentsize + length;
if (currentsize/step!= process) {process = Currentsize/step; if (process% 5 = 0) {//Every%5 progress returns once Listener.ondownloadprogress (mainactivity.ftp_down_loading, process, NULL)
;
}} out.flush ();
Out.close ();
Input.close (); This method is to ensure that the flow is finished, and if this method is not available, it may cause the current program to Die if (Ftpclient.completependingcommand ()) {Listener.ondOwnloadprogress (mainactivity.ftp_down_success, 0, New File (LocalPath));
else {listener.ondownloadprogress (mainactivity.ftp_down_fail, 0, NULL);
After the download is complete, close the connection this.closeconnect ();
Listener.ondownloadprogress (mainactivity.ftp_disconnect_success, 0, NULL);
Return
//-------------------------------------------------------file deletion method------------------------------------------------
/** * Deletes files under FTP. * * @param serverpath * FTP directory and file path * @param listener * listener * @throws IOException/P ublic void Deletesinglefile (String serverpath, Deletefileprogresslistener listener) throws Exception {//Open
FTP Service try {this.openconnect ();
Listener.ondeleteprogress (MAINACTIVITY.FTP_CONNECT_SUCCESSS);
catch (IOException E1) {e1.printstacktrace ();
Listener.ondeleteprogress (Mainactivity.ftp_connect_fail);
Return ///First determine if the server file exists Ftpfile[] files = ftpclient.listfiles (Serverpath);
if (Files.length = = 0) {listener.ondeleteprogress (mainactivity.ftp_file_notexists);
Return
//delete operation Boolean flag = TRUE;
Flag = Ftpclient.deletefile (Serverpath);
if (flag) {listener.ondeleteprogress (mainactivity.ftp_deletefile_success);
else {listener.ondeleteprogress (mainactivity.ftp_deletefile_fail);
///Remove the connection This.closeconnect () after completion;
Listener.ondeleteprogress (mainactivity.ftp_disconnect_success);
Return
//-------------------------------------------------------Turn off connection------------------------------------------------
/** * Open the FTP service. * * @throws IOException/public void Openconnect () throws IOException {//Chinese transcoding Ftpclient.setcontro
Lencoding ("UTF-8"); int reply;
Server response value//Connect to Server Ftpclient.connect (HostName, ServerPort); Get response Value reply = Ftpclient.getreplycodE (); if (!
Ftpreply.ispositivecompletion (Reply)) {//Disconnect connection ftpclient.disconnect ();
throw new IOException ("Connect fail:" + Reply);
//Login to Server Ftpclient.login (userName, password);
Gets the response value reply = Ftpclient.getreplycode (); if (!
Ftpreply.ispositivecompletion (Reply)) {//Disconnect connection ftpclient.disconnect ();
throw new IOException ("Connect fail:" + Reply); else {//Get login information ftpclientconfig config = new Ftpclientconfig (ftpclient. Getsystemtype (). Split (
"") [0]);
Config.setserverlanguagecode ("en");
Ftpclient.configure (config);
Use passive mode to set as Default Ftpclient.enterlocalpassivemode ();
Binary files support ftpclient. Setfiletype (Org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE);
}/** * Closes the FTP service.
* * @throws IOException */public void Closeconnect () throws IOException {if (ftpclient!= null) { Exit FTP FtpclieNt.logout ();
Disconnect the connection ftpclient.disconnect ();
}//---------------------------------------------------upload, download, delete listening--------------------------------------------- * * Upload Progress Monitor/public interface Uploadprogresslistener {public void onuploadprogress (String curre
Ntstep, long uploadsize, file file); * * * Download progress monitor/public interface Downloadprogresslistener {public void ondownloadprogress (String cu
Rrentstep, long downprocess, file file); /* * File deletion listener/public interface Deletefileprogresslistener {public void ondeleteprogress (String cu
RRENTSTEP);
}
}
3. Progressinputstream
Package com.ftp;
Import Java.io.File;
Import java.io.IOException;
Import Java.io.InputStream;
Import Com.ftp.FTP.UploadProgressListener;
Import Android.os.Bundle;
Import Android.os.Handler;
Import Android.os.Message;
Import Android.util.Log; public class Progressinputstream extends InputStream {private static final int ten_kilobytes = 1024 * 10;//10K return per upload
Once private InputStream InputStream;
private long progress;
Private long lastupdate;
Private Boolean closed;
Private Uploadprogresslistener listener;
Private File LocalFile; Public Progressinputstream (InputStream inputstream,uploadprogresslistener listener,file localFile) {This.inputStrea
m = InputStream;
this.progress = 0;
this.lastupdate = 0;
This.listener = listener;
This.localfile = LocalFile;
this.closed = false;
@Override public int Read () throws IOException {int count = Inputstream.read (); Return IncrementcounteraNdupdatedisplay (count); @Override public int read (byte[] b, int off, int len) throws IOException {int count = Inputstream.read (b,
Off, Len);
Return Incrementcounterandupdatedisplay (count);
@Override public void Close () throws IOException {super.close ();
if (closed) throw new IOException ("already closed");
closed = true;
private int Incrementcounterandupdatedisplay (int count) {if (Count > 0) Progress + = count;
Lastupdate = Maybeupdatedisplay (progress, lastupdate);
return count; Private long Maybeupdatedisplay (long progress, long lastupdate) {if (Progress-lastupdate > Ten_kilobytes
) {lastupdate = progress;
This.listener.onUploadProgress (mainactivity.ftp_upload_loading, Progress, this.localfile);
return lastupdate;
}
}
Original link: http://blog.csdn.net/tianyitianyi1/article/details/38637999
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.