Android关于FTP文件上传和下载功能详解

Android关于FTP文件上传和下载功能详解,第1张

概述本文实例为大家分享了Android九宫格图片展示的具体代码,供大家参考,具体内容如下

本文实例为大家分享了AndroID九宫格图片展示的具体代码,供大家参考,具体内容如下

此篇博客为整理文章,供大家学习。

1.首先下载commons-net  jar包,可以百度下载。

FTP的文件上传和下载的工具类:

package ryancheng.example.progressbar;  import java.io.file; import java.io.fileOutputStream; import java.io.inputStream; import java.io.OutputStream; import java.io.RandomAccessfile; 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 androID.os.Environment;  public class FTPManager {  FTPClIEnt ftpClIEnt = null;   public FTPManager() {   ftpClIEnt = new FTPClIEnt();  }   // 连接到ftp服务器  public synchronized boolean connect() throws Exception {   boolean bool = false;   if (ftpClIEnt.isConnected()) {//判断是否已登陆    ftpClIEnt.disconnect();   }   ftpClIEnt.setDataTimeout(20000);//设置连接超时时间   ftpClIEnt.setControlEnCoding("utf-8");   ftpClIEnt.connect("ip地址",端口);   if (FTPReply.isPositiveCompletion(ftpClIEnt.getReplyCode())) {    if (ftpClIEnt.login("用户名","密码")) {     bool = true;     System.out.println("ftp连接成功");    }   }   return bool;  }   // 创建文件夹  public boolean createDirectory(String path) throws Exception {   boolean bool = false;   String directory = path.substring(0,path.lastIndexOf("/") + 1);   int start = 0;   int end = 0;   if (directory.startsWith("/")) {    start = 1;   }   end = directory.indexOf("/",start);   while (true) {    String subdirectory = directory.substring(start,end);    if (!ftpClIEnt.changeWorkingDirectory(subdirectory)) {     ftpClIEnt.makeDirectory(subdirectory);     ftpClIEnt.changeWorkingDirectory(subdirectory);     bool = true;    }    start = end + 1;    end = directory.indexOf("/",start);    if (end == -1) {     break;    }   }   return bool;  }   // 实现上传文件的功能  public synchronized boolean uploadfile(String localPath,String serverPath)    throws Exception {   // 上传文件之前,先判断本地文件是否存在   file localfile = new file(localPath);   if (!localfile.exists()) {    System.out.println("本地文件不存在");    return false;   }   System.out.println("本地文件存在,名称为:" + localfile.getname());   createDirectory(serverPath); // 如果文件夹不存在,创建文件夹   System.out.println("服务器文件存放路径:" + serverPath + localfile.getname());   String filename = localfile.getname();   // 如果本地文件存在,服务器文件也在,上传文件,这个方法中也包括了断点上传   long localSize = localfile.length(); // 本地文件的长度   FTPfile[] files = ftpClIEnt.Listfiles(filename);   long serverSize = 0;   if (files.length == 0) {    System.out.println("服务器文件不存在");    serverSize = 0;   } else {    serverSize = files[0].getSize(); // 服务器文件的长度   }   if (localSize <= serverSize) {    if (ftpClIEnt.deletefile(filename)) {     System.out.println("服务器文件存在,删除文件,开始重新上传");     serverSize = 0;    }   }   RandomAccessfile raf = new RandomAccessfile(localfile,"r");   // 进度   long step = localSize / 100;   long process = 0;   long currentSize = 0;   // 好了,正式开始上传文件   ftpClIEnt.enterLocalPassiveMode();   ftpClIEnt.setfileType(FTP.BINARY_file_TYPE);   ftpClIEnt.setRestartOffset(serverSize);   raf.seek(serverSize);   OutputStream output = ftpClIEnt.appendfileStream(filename);   byte[] b = new byte[1024];   int length = 0;   while ((length = raf.read(b)) != -1) {    output.write(b,length);    currentSize = currentSize + length;    if (currentSize / step != process) {     process = currentSize / step;     if (process % 10 == 0) {      System.out.println("上传进度:" + process);     }    }   }   output.flush();   output.close();   raf.close();   if (ftpClIEnt.completePendingCommand()) {    System.out.println("文件上传成功");    return true;   } else {    System.out.println("文件上传失败");    return false;   }  }   // 实现下载文件功能,可实现断点下载  public synchronized boolean downloadfile(String localPath,String serverPath)    throws Exception {   // 先判断服务器文件是否存在   FTPfile[] files = ftpClIEnt.Listfiles(serverPath);   if (files.length == 0) {    System.out.println("服务器文件不存在");    return false;   }   System.out.println("远程文件存在,名字为:" + files[0].getname());   localPath = localPath + files[0].getname();   // 接着判断下载的文件是否能断点下载   long serverSize = files[0].getSize(); // 获取远程文件的长度   file localfile = new file(localPath);   long localSize = 0;   if (localfile.exists()) {    localSize = localfile.length(); // 如果本地文件存在,获取本地文件的长度    if (localSize >= serverSize) {     System.out.println("文件已经下载完了");     file file = new file(localPath);     file.delete();     System.out.println("本地文件存在,删除成功,开始重新下载");     return false;    }   }   // 进度   long step = serverSize / 100;   long process = 0;   long currentSize = 0;   // 开始准备下载文件   ftpClIEnt.enterLocalActiveMode();   ftpClIEnt.setfileType(FTP.BINARY_file_TYPE);   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,length);    currentSize = currentSize + length;    if (currentSize / step != process) {     process = currentSize / step;     if (process % 10 == 0) {      System.out.println("下载进度:" + process);     }    }   }   out.flush();   out.close();   input.close();   // 此方法是来确保流处理完毕,如果没有此方法,可能会造成现程序死掉   if (ftpClIEnt.completePendingCommand()) {    System.out.println("文件下载成功");    return true;   } else {    System.out.println("文件下载失败");    return false;   }  }   // 如果ftp上传打开,就关闭掉  public voID closeFTP() throws Exception {   if (ftpClIEnt.isConnected()) {    ftpClIEnt.disconnect();   }  } } 

具体实现看代码注释写的很详细。

一.AndroID中FTP文件上传代码:

// 上传例子 private voID ftpUpload() {  new Thread() {  public voID run() {   try {   System.out.println("正在连接ftp服务器....");   FTPManager ftpManager = new FTPManager();   if (ftpManager.connect()) {   if (ftpManager.uploadfile(ftpManager.rootPath + "UpdateXZMarketPlatform.apk","mnt/sdcard/")) {   ftpManager.closeFTP();   }   }   } catch (Exception e) {   // Todo: handle exception   // System.out.println(e.getMessage());   }  }  }.start();  } 

二.AndroID中FTP文件下载代码:

// 下载例子 private voID ftpDownload() {  new Thread() {  public voID run() {   try {   System.out.println("正在连接ftp服务器....");   FTPManager ftpManager = new FTPManager();   if (ftpManager.connect()) {   if (ftpManager.downloadfile(ftpManager.rootPath,"20120723_XFQ07_XZMarketPlatform.db")) {   ftpManager.closeFTP();   }   }   } catch (Exception e) {   // Todo: handle exception   // System.out.println(e.getMessage());   }  }  }.start();  } 

自己之前做项目的时候写过的FTP上传代码:

package com.kandao.yunbell.vIDeocall;  import java.io.file; import java.io.fileinputStream; import java.io.fileNotFoundException; import java.io.IOException; import java.io.UnsupportedEnCodingException; import java.net.socketException;  import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPClIEnt; import org.apache.commons.net.ftp.FTPReply;  import com.kandao.yunbell.common.SysApplication;  import androID.content.Context; import androID.util.Log;  public class MyUploadThread extends Thread {  private String filename;// 文件名字  private String filePath;// 文件本地路径  private String fileStoragePath;// 文件服务器存储路径  private String serverAddress;// 服务器地址  private String ftpUsername;// ftp账号  private String ftpPassword;// ftp密码  private Context mContext;  public MyUploadThread() {   super();   // Todo auto-generated constructor stub  }   public MyUploadThread(Context mContext,String filename,String filePath,String fileStoragePath,String serverAddress,String ftpUsername,String ftpPassword) {   super();   this.filename = filename;   this.filePath = filePath;   this.fileStoragePath = fileStoragePath;   this.serverAddress = serverAddress;   this.ftpUsername = ftpUsername;   this.ftpPassword = ftpPassword;   this.mContext=mContext;  }   @OverrIDe  public voID run() {   super.run();   try {    fileinputStream fis=null;    FTPClIEnt ftpClIEnt = new FTPClIEnt();    String[] IDPort = serverAddress.split(":");    ftpClIEnt.connect(IDPort[0],Integer.parseInt(IDPort[1]));    int returnCode = ftpClIEnt.getReplyCode();    Log.i("caohai","returnCode,upload:"+returnCode);    boolean loginResult = ftpClIEnt.login(ftpUsername,ftpPassword);    Log.i("caohai","loginResult:"+loginResult);    if (loginResult && FTPReply.isPositiveCompletion(returnCode)) {// 如果登录成功          // 设置上传目录          if (((SysApplication) mContext).getIsVIDeo()) {      ((SysApplication) mContext).setIsVIDeo(false);      boolean ff=ftpClIEnt.changeWorkingDirectory(fileStoragePath + "/vIDeo/");      Log.i("caohai","ff:"+ff);     }else{     boolean ee=ftpClIEnt.changeWorkingDirectory(fileStoragePath + "/photo/");     Log.i("caohai","ee:"+ee);     }     ftpClIEnt.setBufferSize(1024);     // ftpClIEnt.setControlEnCoding("iso-8859-1");     // ftpClIEnt.enterLocalPassiveMode();     ftpClIEnt.setfileType(FTP.BINARY_file_TYPE);      fis = new fileinputStream(filePath + "/"       + filename);      Log.i("caohai","fileStoragePath00000:"+fileStoragePath);     String[] path = fileStoragePath.split("visitorRecord");          boolean fs = ftpClIEnt.storefile(new String((path[1]       + "/photo/" + filename).getBytes(),"iso-8859-1"),fis);     Log.i("caohai","shifoushangchuanchenggong:"+fs);     fis.close();     ftpClIEnt.logout();     //ftpClIEnt.disconnect();    } else {// 如果登录失败     ftpClIEnt.disconnect();    }   } catch (NumberFormatException e) {    // Todo auto-generated catch block    e.printstacktrace();   } catch (SocketException e) {    // Todo auto-generated catch block    e.printstacktrace();   } catch (fileNotFoundException e) {    // Todo auto-generated catch block    e.printstacktrace();   } catch (UnsupportedEnCodingException e) {    // Todo auto-generated catch block    e.printstacktrace();   } catch (IOException e) {    // Todo auto-generated catch block    e.printstacktrace();   }   } } 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。

总结

以上是内存溢出为你收集整理的Android关于FTP文件上传和下载功能详解全部内容,希望文章能够帮你解决Android关于FTP文件上传和下载功能详解所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1144444.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-31
下一篇 2022-05-31

发表评论

登录后才能评论

评论列表(0条)

保存