Android中FTP上传、下载的功能实现(含进度)
程序员文章站
2024-04-03 12:41:10
android中使用的ftp上传、下载,含有进度。
代码部分主要分为三个文件:mainactivity,ftp,progressinputstream...
android中使用的ftp上传、下载,含有进度。
代码部分主要分为三个文件: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连接成功"; public static final string ftp_connect_fail = "ftp连接失败"; public static final string ftp_disconnect_success = "ftp断开连接"; public static final string ftp_file_notexists = "ftp上文件不存在"; public static final string ftp_upload_success = "ftp文件上传成功"; public static final string ftp_upload_fail = "ftp文件上传失败"; public static final string ftp_upload_loading = "ftp文件正在上传"; public static final string ftp_down_loading = "ftp文件正在下载"; public static final string ftp_down_success = "ftp文件下载成功"; public static final string ftp_down_fail = "ftp文件下载失败"; public static final string ftp_deletefile_success = "ftp文件删除成功"; public static final string ftp_deletefile_fail = "ftp文件删除失败"; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.main); initview(); } private void initview() { //上传功能 //new ftp().uploadmultifile为多文件上传 //new ftp().uploadsinglefile为单文件上传 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() { // 上传 file file = new file("/mnt/sdcard/ftptest.docx"); try { //单文件上传 new ftp().uploadsinglefile(file, "/fff",new uploadprogresslistener(){ @override public void onuploadprogress(string currentstep,long uploadsize,file file) { // todo auto-generated method stub log.d(tag, currentstep); if(currentstep.equals(mainactivity.ftp_upload_success)){ log.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(); } }); //下载功能 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() { // 下载 try { //单文件下载 new ftp().downloadsinglefile("/fff/ftptest.docx","/mnt/sdcard/download/","ftptest.docx",new downloadprogresslistener(){ @override public void ondownloadprogress(string currentstep, long downprocess, file file) { log.d(tag, currentstep); if(currentstep.equals(mainactivity.ftp_down_success)){ log.d(tag, "-----xiazai--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(); } }); //删除功能 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() { // 删除 try { new ftp().deletesinglefile("/fff/ftptest.docx",new deletefileprogresslistener(){ @override public void ondeleteprogress(string currentstep) { log.d(tag, currentstep); if(currentstep.equals(mainactivity.ftp_deletefile_success)){ log.d(tag, "-----shanchu--success"); } 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 { /** * 服务器名. */ private string hostname; /** * 端口号 */ private int serverport; /** * 用户名. */ private string username; /** * 密码. */ private string password; /** * ftp连接. */ private ftpclient ftpclient; public ftp() { this.hostname = "192.168.1.101"; this.serverport = 21; this.username = "admin"; this.password = "1234"; this.ftpclient = new ftpclient(); } // -------------------------------------------------------文件上传方法------------------------------------------------ /** * 上传单个文件. * * @param localfile * 本地文件 * @param remotepath * ftp目录 * @param listener * 监听器 * @throws ioexception */ public void uploadsinglefile(file singlefile, string remotepath, uploadprogresslistener listener) throws ioexception { // 上传之前初始化 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); } // 上传完成之后关闭连接 this.uploadafteroperate(listener); } /** * 上传多个文件. * * @param localfile * 本地文件 * @param remotepath * ftp目录 * @param listener * 监听器 * @throws ioexception */ public void uploadmultifile(linkedlist<file> filelist, string remotepath, uploadprogresslistener listener) throws ioexception { // 上传之前初始化 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); } } // 上传完成之后关闭连接 this.uploadafteroperate(listener); } /** * 上传单个文件. * * @param localfile * 本地文件 * @return true上传成功, false上传失败 * @throws ioexception */ private boolean uploadingsingle(file localfile, uploadprogresslistener listener) throws ioexception { boolean flag = true; // 不带进度的方式 // // 创建输入流 // inputstream inputstream = new fileinputstream(localfile); // // 上传单个文件 // flag = ftpclient.storefile(localfile.getname(), inputstream); // // 关闭文件流 // inputstream.close(); // 带有进度的方式 bufferedinputstream buffin = new bufferedinputstream( new fileinputstream(localfile)); progressinputstream progressinput = new progressinputstream(buffin, listener, localfile); flag = ftpclient.storefile(localfile.getname(), progressinput); buffin.close(); return flag; } /** * 上传文件之前初始化相关参数 * * @param remotepath * ftp目录 * @param listener * 监听器 * @throws ioexception */ private void uploadbeforeoperate(string remotepath, uploadprogresslistener listener) throws ioexception { // 打开ftp服务 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; } // 设置模式 ftpclient.setfiletransfermode(org.apache.commons.net.ftp.ftp.stream_transfer_mode); // ftp下创建文件夹 ftpclient.makedirectory(remotepath); // 改变ftp目录 ftpclient.changeworkingdirectory(remotepath); // 上传单个文件 } /** * 上传完成之后关闭连接 * * @param listener * @throws ioexception */ private void uploadafteroperate(uploadprogresslistener listener) throws ioexception { this.closeconnect(); listener.onuploadprogress(mainactivity.ftp_disconnect_success, 0, null); } // -------------------------------------------------------文件下载方法------------------------------------------------ /** * 下载单个文件,可实现断点下载. * * @param serverpath * ftp目录及文件路径 * @param localpath * 本地目录 * @param filename * 下载之后的文件名称 * @param listener * 监听器 * @throws ioexception */ public void downloadsinglefile(string serverpath, string localpath, string filename, downloadprogresslistener listener) throws exception { // 打开ftp服务 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; } // 先判断服务器文件是否存在 ftpfile[] files = ftpclient.listfiles(serverpath); if (files.length == 0) { listener.ondownloadprogress(mainactivity.ftp_file_notexists, 0, null); return; } //创建本地文件夹 file mkfile = new file(localpath); if (!mkfile.exists()) { mkfile.mkdirs(); } localpath = localpath + filename; // 接着判断下载的文件是否能断点下载 long serversize = files[0].getsize(); // 获取远程文件的长度 file localfile = new file(localpath); long localsize = 0; if (localfile.exists()) { localsize = localfile.length(); // 如果本地文件存在,获取本地文件的长度 if (localsize >= serversize) { file file = new file(localpath); file.delete(); } } // 进度 long step = serversize / 100; long process = 0; long currentsize = 0; // 开始准备下载文件 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) { //每隔%5的进度返回一次 listener.ondownloadprogress(mainactivity.ftp_down_loading, process, null); } } } out.flush(); out.close(); input.close(); // 此方法是来确保流处理完毕,如果没有此方法,可能会造成现程序死掉 if (ftpclient.completependingcommand()) { listener.ondownloadprogress(mainactivity.ftp_down_success, 0, new file(localpath)); } else { listener.ondownloadprogress(mainactivity.ftp_down_fail, 0, null); } // 下载完成之后关闭连接 this.closeconnect(); listener.ondownloadprogress(mainactivity.ftp_disconnect_success, 0, null); return; } // -------------------------------------------------------文件删除方法------------------------------------------------ /** * 删除ftp下的文件. * * @param serverpath * ftp目录及文件路径 * @param listener * 监听器 * @throws ioexception */ public void deletesinglefile(string serverpath, deletefileprogresslistener listener) throws exception { // 打开ftp服务 try { this.openconnect(); listener.ondeleteprogress(mainactivity.ftp_connect_successs); } catch (ioexception e1) { e1.printstacktrace(); listener.ondeleteprogress(mainactivity.ftp_connect_fail); return; } // 先判断服务器文件是否存在 ftpfile[] files = ftpclient.listfiles(serverpath); if (files.length == 0) { listener.ondeleteprogress(mainactivity.ftp_file_notexists); return; } //进行删除操作 boolean flag = true; flag = ftpclient.deletefile(serverpath); if (flag) { listener.ondeleteprogress(mainactivity.ftp_deletefile_success); } else { listener.ondeleteprogress(mainactivity.ftp_deletefile_fail); } // 删除完成之后关闭连接 this.closeconnect(); listener.ondeleteprogress(mainactivity.ftp_disconnect_success); return; } // -------------------------------------------------------打开关闭连接------------------------------------------------ /** * 打开ftp服务. * * @throws ioexception */ public void openconnect() throws ioexception { // 中文转码 ftpclient.setcontrolencoding("utf-8"); int reply; // 服务器响应值 // 连接至服务器 ftpclient.connect(hostname, serverport); // 获取响应值 reply = ftpclient.getreplycode(); if (!ftpreply.ispositivecompletion(reply)) { // 断开连接 ftpclient.disconnect(); throw new ioexception("connect fail: " + reply); } // 登录到服务器 ftpclient.login(username, password); // 获取响应值 reply = ftpclient.getreplycode(); if (!ftpreply.ispositivecompletion(reply)) { // 断开连接 ftpclient.disconnect(); throw new ioexception("connect fail: " + reply); } else { // 获取登录信息 ftpclientconfig config = new ftpclientconfig(ftpclient .getsystemtype().split(" ")[0]); config.setserverlanguagecode("zh"); ftpclient.configure(config); // 使用被动模式设为默认 ftpclient.enterlocalpassivemode(); // 二进制文件支持 ftpclient .setfiletype(org.apache.commons.net.ftp.ftp.binary_file_type); } } /** * 关闭ftp服务. * * @throws ioexception */ public void closeconnect() throws ioexception { if (ftpclient != null) { // 退出ftp ftpclient.logout(); // 断开连接 ftpclient.disconnect(); } } // ---------------------------------------------------上传、下载、删除监听--------------------------------------------- /* * 上传进度监听 */ public interface uploadprogresslistener { public void onuploadprogress(string currentstep, long uploadsize, file file); } /* * 下载进度监听 */ public interface downloadprogresslistener { public void ondownloadprogress(string currentstep, long downprocess, file file); } /* * 文件删除监听 */ public interface deletefileprogresslistener { public void ondeleteprogress(string currentstep); } }
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返回一次 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.inputstream = 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; } }
原文链接:http://blog.csdn.net/tianyitianyi1/article/details/38637999
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
上一篇: Android应用开发中控制反转IoC设计模式使用教程
下一篇: MySQL远程访问设置终极方法