Android关于FTP文件上传和下载功能详解
作者:一诺的秘密花园 发布时间:2021-06-02 18:15:55
标签:Android,FTP,上传,下载
本文实例为大家分享了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();
}
}
}
来源:http://blog.csdn.net/mr_jianrong/article/details/78049178


猜你喜欢
- 上一篇:瑞吉外卖项目:新增员工一. 员工信息分页查询1. 需求分析当系统中的用户越来越多页面展示不完整,我们需要通过实现分页的方式去展示员工
- 本文将通过阅读spring源码,分析@Bean注解导入Bean的原理。从AnnotationConfigApplicationContext
- 开发过程中会遇见很多app注册时,需要通过手机发送验证码验证 ,这是可以封装一个验证码按钮:attrs.xml<?xml versio
- 一、准备工作mybatis-plus作为mybatis的增强工具,它的出现极大的简化了开发中的数据库操作,但是长久以来,它的联表查询能力一直
- 本文实例为大家分享了java实现猜拳游戏的具体代码,供大家参考,具体内容如下package com.farsight.session7;im
- 问题描述通过FeignClient调用微服务提供的分页对象IPage报错{"message": "Type d
- 这篇文章主要介绍了Spring boot @RequestBody数据传递过程详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有
- 具体步骤:1.创建一个maven项目 spring-day1-constructor2.导入依赖 <prop
- 需求:键盘录入一个月份,输出该月份对应的季节。一年有四季3,4,5 春季6,7,8 夏季9,
- 对JVM运行参数进行修改是JVM性能调优的重要手段,下面介绍在应用程序开发过程中JVM参数设置的几种方式。方式一java程序运行时指定 -D
- 数组分页查询出全部数据,然后再list中截取需要的部分。mybatis接口List<Student> queryStudents
- Flutter中的默认导航分成两种,一种是命名的路由,一种是构建路由。一、命名路由传参应用入口处定义路由表class MyApp exten
- 一、引言以前在饿了么上面订餐的时候,曾经看到过这么一个特效,就是将商品加入订单时,会有一个小球呈抛物线状落入购物车中,然后购物车中的数量会改
- C#中常涉及到对用户密码的加密于解密的算法,其中使用MD5加密是最常见的的实现方式。本文总结了通用的算法并结合了自己的一点小经验,分享给大家
- Spring Boot可以和大部分流行的测试框架协同工作:通过Spring JUnit创建单元测试;生成测试数据初始化数据库用于测试;Spr
- 多级缓存在实际开发项目,为了减少数据库的访问压力,都会将数据缓存到内存中比如:Redis(分布式缓存)、EHCHE(JVM内置缓存).例如在
- 本文实例讲述了Android TextView中文字通过SpannableString设置属性的方法。分享给大家供大家参考,具体如下:在An
- 前言RadioGroup是继承LinearLayout,只支持横向或者竖向两种布局。所以在某些情况,比如多行多列布局,RadioGroup就
- Android实现读取NFC卡卡号示例,具体如下:1.权限 <uses-permission android:name=&
- 前言作为一个写java的使用最多的轻量级框架莫过于spring,不管是老项目用到的springmvc,还是现在流行的springboot,都