Android中关于FTP的文件上传和下载

来源:互联网 发布:php 析构函数的用法 编辑:程序博客网 时间:2024/06/06 08:43

Android中关于FTP的文件上传和下载

此篇博客为整理文章,文章出处:http://www.cnblogs.com/xyc20080413/archive/2013/04/08/3008646.html
1.首先下载commons-net  jar包,可以百度下载。
FTP的文件上传和下载的工具类:
[java] view plain copy
  1. package ryancheng.example.progressbar;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileOutputStream;  
  5. import java.io.InputStream;  
  6. import java.io.OutputStream;  
  7. import java.io.RandomAccessFile;  
  8. import org.apache.commons.net.ftp.FTP;  
  9. import org.apache.commons.net.ftp.FTPClient;  
  10. import org.apache.commons.net.ftp.FTPFile;  
  11. import org.apache.commons.net.ftp.FTPReply;  
  12. import android.os.Environment;  
  13.   
  14. public class FTPManager {  
  15.     FTPClient ftpClient = null;  
  16.   
  17.     public FTPManager() {  
  18.         ftpClient = new FTPClient();  
  19.     }  
  20.   
  21.     // 连接到ftp服务器  
  22.     public synchronized boolean connect() throws Exception {  
  23.         boolean bool = false;  
  24.         if (ftpClient.isConnected()) {//判断是否已登陆  
  25.             ftpClient.disconnect();  
  26.         }  
  27.         ftpClient.setDataTimeout(20000);//设置连接超时时间  
  28.         ftpClient.setControlEncoding("utf-8");  
  29.         ftpClient.connect("ip地址", 端口);  
  30.         if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {  
  31.             if (ftpClient.login("用户名""密码")) {  
  32.                 bool = true;  
  33.                 System.out.println("ftp连接成功");  
  34.             }  
  35.         }  
  36.         return bool;  
  37.     }  
  38.   
  39.     // 创建文件夹  
  40.     public boolean createDirectory(String path) throws Exception {  
  41.         boolean bool = false;  
  42.         String directory = path.substring(0, path.lastIndexOf("/") + 1);  
  43.         int start = 0;  
  44.         int end = 0;  
  45.         if (directory.startsWith("/")) {  
  46.             start = 1;  
  47.         }  
  48.         end = directory.indexOf("/", start);  
  49.         while (true) {  
  50.             String subDirectory = directory.substring(start, end);  
  51.             if (!ftpClient.changeWorkingDirectory(subDirectory)) {  
  52.                 ftpClient.makeDirectory(subDirectory);  
  53.                 ftpClient.changeWorkingDirectory(subDirectory);  
  54.                 bool = true;  
  55.             }  
  56.             start = end + 1;  
  57.             end = directory.indexOf("/", start);  
  58.             if (end == -1) {  
  59.                 break;  
  60.             }  
  61.         }  
  62.         return bool;  
  63.     }  
  64.   
  65.     // 实现上传文件的功能  
  66.     public synchronized boolean uploadFile(String localPath, String serverPath)  
  67.             throws Exception {  
  68.         // 上传文件之前,先判断本地文件是否存在  
  69.         File localFile = new File(localPath);  
  70.         if (!localFile.exists()) {  
  71.             System.out.println("本地文件不存在");  
  72.             return false;  
  73.         }  
  74.         System.out.println("本地文件存在,名称为:" + localFile.getName());  
  75.         createDirectory(serverPath); // 如果文件夹不存在,创建文件夹  
  76.         System.out.println("服务器文件存放路径:" + serverPath + localFile.getName());  
  77.         String fileName = localFile.getName();  
  78.         // 如果本地文件存在,服务器文件也在,上传文件,这个方法中也包括了断点上传  
  79.         long localSize = localFile.length(); // 本地文件的长度  
  80.         FTPFile[] files = ftpClient.listFiles(fileName);  
  81.         long serverSize = 0;  
  82.         if (files.length == 0) {  
  83.             System.out.println("服务器文件不存在");  
  84.             serverSize = 0;  
  85.         } else {  
  86.             serverSize = files[0].getSize(); // 服务器文件的长度  
  87.         }  
  88.         if (localSize <= serverSize) {  
  89.             if (ftpClient.deleteFile(fileName)) {  
  90.                 System.out.println("服务器文件存在,删除文件,开始重新上传");  
  91.                 serverSize = 0;  
  92.             }  
  93.         }  
  94.         RandomAccessFile raf = new RandomAccessFile(localFile, "r");  
  95.         // 进度  
  96.         long step = localSize / 100;  
  97.         long process = 0;  
  98.         long currentSize = 0;  
  99.         // 好了,正式开始上传文件  
  100.         ftpClient.enterLocalPassiveMode();  
  101.         ftpClient.setFileType(FTP.BINARY_FILE_TYPE);  
  102.         ftpClient.setRestartOffset(serverSize);  
  103.         raf.seek(serverSize);  
  104.         OutputStream output = ftpClient.appendFileStream(fileName);  
  105.         byte[] b = new byte[1024];  
  106.         int length = 0;  
  107.         while ((length = raf.read(b)) != -1) {  
  108.             output.write(b, 0, length);  
  109.             currentSize = currentSize + length;  
  110.             if (currentSize / step != process) {  
  111.                 process = currentSize / step;  
  112.                 if (process % 10 == 0) {  
  113.                     System.out.println("上传进度:" + process);  
  114.                 }  
  115.             }  
  116.         }  
  117.         output.flush();  
  118.         output.close();  
  119.         raf.close();  
  120.         if (ftpClient.completePendingCommand()) {  
  121.             System.out.println("文件上传成功");  
  122.             return true;  
  123.         } else {  
  124.             System.out.println("文件上传失败");  
  125.             return false;  
  126.         }  
  127.     }  
  128.   
  129.     // 实现下载文件功能,可实现断点下载  
  130.     public synchronized boolean downloadFile(String localPath, String serverPath)  
  131.             throws Exception {  
  132.         // 先判断服务器文件是否存在  
  133.         FTPFile[] files = ftpClient.listFiles(serverPath);  
  134.         if (files.length == 0) {  
  135.             System.out.println("服务器文件不存在");  
  136.             return false;  
  137.         }  
  138.         System.out.println("远程文件存在,名字为:" + files[0].getName());  
  139.         localPath = localPath + files[0].getName();  
  140.         // 接着判断下载的文件是否能断点下载  
  141.         long serverSize = files[0].getSize(); // 获取远程文件的长度  
  142.         File localFile = new File(localPath);  
  143.         long localSize = 0;  
  144.         if (localFile.exists()) {  
  145.             localSize = localFile.length(); // 如果本地文件存在,获取本地文件的长度  
  146.             if (localSize >= serverSize) {  
  147.                 System.out.println("文件已经下载完了");  
  148.                 File file = new File(localPath);  
  149.                 file.delete();  
  150.                 System.out.println("本地文件存在,删除成功,开始重新下载");  
  151.                 return false;  
  152.             }  
  153.         }  
  154.         // 进度  
  155.         long step = serverSize / 100;  
  156.         long process = 0;  
  157.         long currentSize = 0;  
  158.         // 开始准备下载文件  
  159.         ftpClient.enterLocalActiveMode();  
  160.         ftpClient.setFileType(FTP.BINARY_FILE_TYPE);  
  161.         OutputStream out = new FileOutputStream(localFile, true);  
  162.         ftpClient.setRestartOffset(localSize);  
  163.         InputStream input = ftpClient.retrieveFileStream(serverPath);  
  164.         byte[] b = new byte[1024];  
  165.         int length = 0;  
  166.         while ((length = input.read(b)) != -1) {  
  167.             out.write(b, 0, length);  
  168.             currentSize = currentSize + length;  
  169.             if (currentSize / step != process) {  
  170.                 process = currentSize / step;  
  171.                 if (process % 10 == 0) {  
  172.                     System.out.println("下载进度:" + process);  
  173.                 }  
  174.             }  
  175.         }  
  176.         out.flush();  
  177.         out.close();  
  178.         input.close();  
  179.         // 此方法是来确保流处理完毕,如果没有此方法,可能会造成现程序死掉  
  180.         if (ftpClient.completePendingCommand()) {  
  181.             System.out.println("文件下载成功");  
  182.             return true;  
  183.         } else {  
  184.             System.out.println("文件下载失败");  
  185.             return false;  
  186.         }  
  187.     }  
  188.   
  189.     // 如果ftp上传打开,就关闭掉  
  190.     public void closeFTP() throws Exception {  
  191.         if (ftpClient.isConnected()) {  
  192.             ftpClient.disconnect();  
  193.         }  
  194.     }  
  195. }  
具体实现看代码注释写的很详细。

一.Android中FTP文件上传代码:
[java] view plain copy
  1. // 上传例子  
  2. private void ftpUpload() {  
  3.    new Thread() {  
  4.     public void run() {  
  5.      try {  
  6.       System.out.println("正在连接ftp服务器....");  
  7.       FTPManager ftpManager = new FTPManager();  
  8.       if (ftpManager.connect()) {  
  9.        if (ftpManager.uploadFile(ftpManager.rootPath + "UpdateXZMarketPlatform.apk""mnt/sdcard/")) {  
  10.         ftpManager.closeFTP();  
  11.        }  
  12.       }  
  13.      } catch (Exception e) {  
  14.       // TODO: handle exception  
  15.       // System.out.println(e.getMessage());  
  16.      }  
  17.     }  
  18.    }.start();  
  19.  }  


二.Android中FTP文件下载代码:
[java] view plain copy
  1. // 下载例子  
  2. private void ftpDownload() {  
  3.    new Thread() {  
  4.     public void run() {  
  5.      try {  
  6.       System.out.println("正在连接ftp服务器....");  
  7.       FTPManager ftpManager = new FTPManager();  
  8.       if (ftpManager.connect()) {  
  9.        if (ftpManager.downloadFile(ftpManager.rootPath, "20120723_XFQ07_XZMarketPlatform.db")) {  
  10.         ftpManager.closeFTP();  
  11.        }  
  12.       }  
  13.      } catch (Exception e) {  
  14.       // TODO: handle exception  
  15.       // System.out.println(e.getMessage());  
  16.      }  
  17.     }  
  18.    }.start();  
  19.  }  


自己之前做项目的时候写过的FTP上传代码:
[java] view plain copy
  1. package com.kandao.yunbell.videocall;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileInputStream;  
  5. import java.io.FileNotFoundException;  
  6. import java.io.IOException;  
  7. import java.io.UnsupportedEncodingException;  
  8. import java.net.SocketException;  
  9.   
  10. import org.apache.commons.net.ftp.FTP;  
  11. import org.apache.commons.net.ftp.FTPClient;  
  12. import org.apache.commons.net.ftp.FTPReply;  
  13.   
  14. import com.kandao.yunbell.common.SysApplication;  
  15.   
  16. import android.content.Context;  
  17. import android.util.Log;  
  18.   
  19. public class MyUploadThread extends Thread {  
  20.     private String fileName;// 文件名字  
  21.     private String filePath;// 文件本地路径  
  22.     private String fileStoragePath;// 文件服务器存储路径  
  23.     private String serverAddress;// 服务器地址  
  24.     private String ftpUserName;// ftp账号  
  25.     private String ftpPassword;// ftp密码  
  26.     private Context mContext;  
  27.     public MyUploadThread() {  
  28.         super();  
  29.         // TODO Auto-generated constructor stub  
  30.     }  
  31.   
  32.     public MyUploadThread(Context mContext,String fileName, String filePath,  
  33.              String fileStoragePath,String serverAddress,String ftpUserName,String ftpPassword) {  
  34.         super();  
  35.         this.fileName = fileName;  
  36.         this.filePath = filePath;  
  37.         this.fileStoragePath = fileStoragePath;  
  38.         this.serverAddress = serverAddress;  
  39.         this.ftpUserName = ftpUserName;  
  40.         this.ftpPassword = ftpPassword;  
  41.         this.mContext=mContext;  
  42.     }  
  43.   
  44.     @Override  
  45.     public void run() {  
  46.         super.run();  
  47.         try {  
  48.             FileInputStream fis=null;  
  49.             FTPClient ftpClient = new FTPClient();  
  50.             String[] idPort = serverAddress.split(":");  
  51.             ftpClient.connect(idPort[0], Integer.parseInt(idPort[1]));  
  52.             int returnCode = ftpClient.getReplyCode();  
  53.             Log.i("caohai""returnCode,upload:"+returnCode);  
  54.             boolean loginResult = ftpClient.login(ftpUserName, ftpPassword);  
  55.             Log.i("caohai""loginResult:"+loginResult);  
  56.             if (loginResult && FTPReply.isPositiveCompletion(returnCode)) {// 如果登录成功  
  57.                   
  58.                 // 设置上传目录  
  59.                   
  60.                 if (((SysApplication) mContext).getIsVideo()) {  
  61.                     ((SysApplication) mContext).setIsVideo(false);  
  62.                     boolean ff=ftpClient.changeWorkingDirectory(fileStoragePath + "/video/");  
  63.                     Log.i("caohai""ff:"+ff);  
  64.                 }else{  
  65.                 boolean ee=ftpClient.changeWorkingDirectory(fileStoragePath + "/photo/");  
  66.                 Log.i("caohai""ee:"+ee);  
  67.                 }  
  68.                 ftpClient.setBufferSize(1024);  
  69.                 // ftpClient.setControlEncoding("iso-8859-1");  
  70.                 // ftpClient.enterLocalPassiveMode();  
  71.                 ftpClient.setFileType(FTP.BINARY_FILE_TYPE);  
  72.                  fis = new FileInputStream(filePath + "/"  
  73.                         + fileName);  
  74.                  Log.i("caohai""fileStoragePath00000:"+fileStoragePath);  
  75.                 String[] path = fileStoragePath.split("visitorRecord");  
  76.                   
  77.                 boolean fs = ftpClient.storeFile(new String((path[1]  
  78.                         + "/photo/" + fileName).getBytes(), "iso-8859-1"), fis);  
  79.                 Log.i("caohai""shifoushangchuanchenggong:"+fs);  
  80.                 fis.close();  
  81.                 ftpClient.logout();  
  82.                 //ftpClient.disconnect();  
  83.             } else {// 如果登录失败  
  84.                 ftpClient.disconnect();  
  85.             }  
  86.         } catch (NumberFormatException e) {  
  87.             // TODO Auto-generated catch block  
  88.             e.printStackTrace();  
  89.         } catch (SocketException e) {  
  90.             // TODO Auto-generated catch block  
  91.             e.printStackTrace();  
  92.         } catch (FileNotFoundException e) {  
  93.             // TODO Auto-generated catch block  
  94.             e.printStackTrace();  
  95.         } catch (UnsupportedEncodingException e) {  
  96.             // TODO Auto-generated catch block  
  97.             e.printStackTrace();  
  98.         } catch (IOException e) {  
  99.             // TODO Auto-generated catch block  
  100.             e.printStackTrace();  
  101.         }  
  102.   
  103.     }  
  104. }