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

发布时间 - 2026-01-11 03:21:43    点击率:

本文实例为大家分享了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, 0, 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, 0, 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方式实现文件上传和下载功能  # Android实现简单的文件下载与上传  # Android实现文件上传和下载倒计时功能的圆形进度条  # Android Http实现文件的上传和下载  # 使用Android的OkHttp包实现基于HTTP协议的文件上传下载  # Android 文件分段上传和下载实现方案  # 上传  # 不存在  # 上传文件  # 是否存在  # 好了  # 也在  # 如果没有  # 中也  # 大家分享  # 连接到  # 是否能  # 写过  # 死掉  # 具体内容  # 大家多多  # 重新下载  # 判断是否  # 文件服务器  # 九宫格 


相关栏目: 【 网站优化151355 】 【 网络推广146373 】 【 网络技术251813 】 【 AI营销90571


相关推荐: 微博html5版本怎么弄发超话_超话进入入口及发帖格式要求【教程】  如何用AI帮你把自己的生活经历写成一个有趣的故事?  Laravel怎么防止CSRF攻击_Laravel CSRF保护中间件原理与实践  Laravel如何实现多对多模型关联?(Eloquent教程)  使用C语言编写圣诞表白程序  为什么php本地部署后css不生效_静态资源加载失败修复技巧【技巧】  敲碗10年!Mac系列传将迎来「触控与联网」双革新  html5audio标签播放结束怎么触发事件_onended回调方法【教程】  微信小程序 闭包写法详细介绍  Laravel如何使用Seeder填充数据_Laravel模型工厂Factory批量生成测试数据【方法】  Laravel如何处理JSON字段的查询和更新_Laravel JSON列操作与查询技巧  如何在建站宝盒中设置产品搜索功能?  品牌网站制作公司有哪些,买正品品牌一般去哪个网站买?  济南网站建设制作公司,室内设计网站一般都有哪些功能?  如何快速搭建安全的FTP站点?  作用域操作符会触发自动加载吗_php类自动加载机制与::调用【教程】  如何在 Python 中将列表项按字母顺序编号(a.、b.、c. …)  JS碰撞运动实现方法详解  浅谈redis在项目中的应用  如何用PHP快速搭建CMS系统?  如何快速建站并高效导出源代码?  矢量图网站制作软件,用千图网的一张矢量图做公司app首页,该网站并未说明版权等问题,这样做算不算侵权?应该如何解决?  如何在万网利用已有域名快速建站?  实例解析Array和String方法  java ZXing生成二维码及条码实例分享  如何正确选择百度移动适配建站域名?  canvas 画布在主流浏览器中的尺寸限制详细介绍  Midjourney怎样加参数调细节_Midjourney参数调整技巧【指南】  html5源代码发行怎么设置权限_访问权限控制方法与实践【指南】  香港代理服务器配置指南:高匿IP选择、跨境加速与SEO优化技巧  Laravel Eloquent模型如何创建_Laravel ORM基础之Model创建与使用教程  Laravel Artisan命令怎么自定义_创建自己的Laravel命令行工具完全指南  Win11搜索不到蓝牙耳机怎么办 Win11蓝牙驱动更新修复【详解】  网易LOFTER官网链接 老福特网页版登录地址  Laravel如何配置.env文件管理环境变量_Laravel环境变量使用与安全管理  Laravel如何实现数据导出到PDF_Laravel使用snappy生成网页快照PDF【方案】  javascript中的try catch异常捕获机制用法分析  个人摄影网站制作流程,摄影爱好者都去什么网站?  JavaScript实现Fly Bird小游戏  如何在Windows环境下新建FTP站点并设置权限?  Laravel集合Collection怎么用_Laravel集合常用函数详解  JS中对数组元素进行增删改移的方法总结  利用JavaScript实现拖拽改变元素大小  Laravel Octane如何提升性能_使用Laravel Octane加速你的应用  Laravel如何处理JSON字段_Eloquent原生JSON字段类型操作教程  如何注册花生壳免费域名并搭建个人网站?  Laravel Admin后台管理框架推荐_Laravel快速开发后台工具  百度浏览器网页无法复制文字怎么办 百度浏览器复制修复  如何在云主机快速搭建网站站点?  如何批量查询域名的建站时间记录?