Android关于FTP文件上传和下载功能详解
本文实例为大家分享了Android九宫格图片展示的具体代码,供大家参考,具体内容如下
此篇博客为整理文章,供大家学习。
1.首先下载commons-net jar包,可以百度下载。
FTP的文件上传和下载的工具类:
packageryancheng.example.progressbar;
importjava.io.File;
importjava.io.FileOutputStream;
importjava.io.InputStream;
importjava.io.OutputStream;
importjava.io.RandomAccessFile;
importorg.apache.commons.net.ftp.FTP;
importorg.apache.commons.net.ftp.FTPClient;
importorg.apache.commons.net.ftp.FTPFile;
importorg.apache.commons.net.ftp.FTPReply;
importandroid.os.Environment;
publicclassFTPManager{
FTPClientftpClient=null;
publicFTPManager(){
ftpClient=newFTPClient();
}
//连接到ftp服务器
publicsynchronizedbooleanconnect()throwsException{
booleanbool=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连接成功");
}
}
returnbool;
}
//创建文件夹
publicbooleancreateDirectory(Stringpath)throwsException{
booleanbool=false;
Stringdirectory=path.substring(0,path.lastIndexOf("/")+1);
intstart=0;
intend=0;
if(directory.startsWith("/")){
start=1;
}
end=directory.indexOf("/",start);
while(true){
StringsubDirectory=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;
}
}
returnbool;
}
//实现上传文件的功能
publicsynchronizedbooleanuploadFile(StringlocalPath,StringserverPath)
throwsException{
//上传文件之前,先判断本地文件是否存在
FilelocalFile=newFile(localPath);
if(!localFile.exists()){
System.out.println("本地文件不存在");
returnfalse;
}
System.out.println("本地文件存在,名称为:"+localFile.getName());
createDirectory(serverPath);//如果文件夹不存在,创建文件夹
System.out.println("服务器文件存放路径:"+serverPath+localFile.getName());
StringfileName=localFile.getName();
//如果本地文件存在,服务器文件也在,上传文件,这个方法中也包括了断点上传
longlocalSize=localFile.length();//本地文件的长度
FTPFile[]files=ftpClient.listFiles(fileName);
longserverSize=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;
}
}
RandomAccessFileraf=newRandomAccessFile(localFile,"r");
//进度
longstep=localSize/100;
longprocess=0;
longcurrentSize=0;
//好了,正式开始上传文件
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.setRestartOffset(serverSize);
raf.seek(serverSize);
OutputStreamoutput=ftpClient.appendFileStream(fileName);
byte[]b=newbyte[1024];
intlength=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("文件上传成功");
returntrue;
}else{
System.out.println("文件上传失败");
returnfalse;
}
}
//实现下载文件功能,可实现断点下载
publicsynchronizedbooleandownloadFile(StringlocalPath,StringserverPath)
throwsException{
//先判断服务器文件是否存在
FTPFile[]files=ftpClient.listFiles(serverPath);
if(files.length==0){
System.out.println("服务器文件不存在");
returnfalse;
}
System.out.println("远程文件存在,名字为:"+files[0].getName());
localPath=localPath+files[0].getName();
//接着判断下载的文件是否能断点下载
longserverSize=files[0].getSize();//获取远程文件的长度
FilelocalFile=newFile(localPath);
longlocalSize=0;
if(localFile.exists()){
localSize=localFile.length();//如果本地文件存在,获取本地文件的长度
if(localSize>=serverSize){
System.out.println("文件已经下载完了");
Filefile=newFile(localPath);
file.delete();
System.out.println("本地文件存在,删除成功,开始重新下载");
returnfalse;
}
}
//进度
longstep=serverSize/100;
longprocess=0;
longcurrentSize=0;
//开始准备下载文件
ftpClient.enterLocalActiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
OutputStreamout=newFileOutputStream(localFile,true);
ftpClient.setRestartOffset(localSize);
InputStreaminput=ftpClient.retrieveFileStream(serverPath);
byte[]b=newbyte[1024];
intlength=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("文件下载成功");
returntrue;
}else{
System.out.println("文件下载失败");
returnfalse;
}
}
//如果ftp上传打开,就关闭掉
publicvoidcloseFTP()throwsException{
if(ftpClient.isConnected()){
ftpClient.disconnect();
}
}
}
具体实现看代码注释写的很详细。
一.Android中FTP文件上传代码:
//上传例子
privatevoidftpUpload(){
newThread(){
publicvoidrun(){
try{
System.out.println("正在连接ftp服务器....");
FTPManagerftpManager=newFTPManager();
if(ftpManager.connect()){
if(ftpManager.uploadFile(ftpManager.rootPath+"UpdateXZMarketPlatform.apk","mnt/sdcard/")){
ftpManager.closeFTP();
}
}
}catch(Exceptione){
//TODO:handleexception
//System.out.println(e.getMessage());
}
}
}.start();
}
二.Android中FTP文件下载代码:
//下载例子
privatevoidftpDownload(){
newThread(){
publicvoidrun(){
try{
System.out.println("正在连接ftp服务器....");
FTPManagerftpManager=newFTPManager();
if(ftpManager.connect()){
if(ftpManager.downloadFile(ftpManager.rootPath,"20120723_XFQ07_XZMarketPlatform.db")){
ftpManager.closeFTP();
}
}
}catch(Exceptione){
//TODO:handleexception
//System.out.println(e.getMessage());
}
}
}.start();
}
自己之前做项目的时候写过的FTP上传代码:
packagecom.kandao.yunbell.videocall;
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.FileNotFoundException;
importjava.io.IOException;
importjava.io.UnsupportedEncodingException;
importjava.net.SocketException;
importorg.apache.commons.net.ftp.FTP;
importorg.apache.commons.net.ftp.FTPClient;
importorg.apache.commons.net.ftp.FTPReply;
importcom.kandao.yunbell.common.SysApplication;
importandroid.content.Context;
importandroid.util.Log;
publicclassMyUploadThreadextendsThread{
privateStringfileName;//文件名字
privateStringfilePath;//文件本地路径
privateStringfileStoragePath;//文件服务器存储路径
privateStringserverAddress;//服务器地址
privateStringftpUserName;//ftp账号
privateStringftpPassword;//ftp密码
privateContextmContext;
publicMyUploadThread(){
super();
//TODOAuto-generatedconstructorstub
}
publicMyUploadThread(ContextmContext,StringfileName,StringfilePath,
StringfileStoragePath,StringserverAddress,StringftpUserName,StringftpPassword){
super();
this.fileName=fileName;
this.filePath=filePath;
this.fileStoragePath=fileStoragePath;
this.serverAddress=serverAddress;
this.ftpUserName=ftpUserName;
this.ftpPassword=ftpPassword;
this.mContext=mContext;
}
@Override
publicvoidrun(){
super.run();
try{
FileInputStreamfis=null;
FTPClientftpClient=newFTPClient();
String[]idPort=serverAddress.split(":");
ftpClient.connect(idPort[0],Integer.parseInt(idPort[1]));
intreturnCode=ftpClient.getReplyCode();
Log.i("caohai","returnCode,upload:"+returnCode);
booleanloginResult=ftpClient.login(ftpUserName,ftpPassword);
Log.i("caohai","loginResult:"+loginResult);
if(loginResult&&FTPReply.isPositiveCompletion(returnCode)){//如果登录成功
//设置上传目录
if(((SysApplication)mContext).getIsVideo()){
((SysApplication)mContext).setIsVideo(false);
booleanff=ftpClient.changeWorkingDirectory(fileStoragePath+"/video/");
Log.i("caohai","ff:"+ff);
}else{
booleanee=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=newFileInputStream(filePath+"/"
+fileName);
Log.i("caohai","fileStoragePath00000:"+fileStoragePath);
String[]path=fileStoragePath.split("visitorRecord");
booleanfs=ftpClient.storeFile(newString((path[1]
+"/photo/"+fileName).getBytes(),"iso-8859-1"),fis);
Log.i("caohai","shifoushangchuanchenggong:"+fs);
fis.close();
ftpClient.logout();
//ftpClient.disconnect();
}else{//如果登录失败
ftpClient.disconnect();
}
}catch(NumberFormatExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}catch(SocketExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}catch(FileNotFoundExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}catch(UnsupportedEncodingExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}catch(IOExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。