1. 程式人生 > 程式設計 >Android使用ftp方式實現檔案上傳和下載

Android使用ftp方式實現檔案上傳和下載

近期在工作上一直再維護平臺OTA線上升級專案,其中關於這個升級檔案主要是存放於ftp伺服器上的,然後客戶端通過走ftp協議方式下載至本地Android機進行一個系統升級操作。那麼今天將對ftp實現檔案上傳和下載進行一個使用總結,關於ftp這方面的理論知識如果不是太瞭解的各位道友,那麼請移步HTTP和FTP的區別的一些理論知識 作個具體的瞭解或者查閱相關資料。那麼先看看個人工作專案這個OTA升級效果圖吧。如下:

這裡寫圖片描述

下面是具體的介面實現:

這裡寫圖片描述

那麼相關ftp的操作,已經被封裝到ota.ftp這個包下,各位童鞋可以下載示例程式碼慢慢研究。另外這個要是用ftp服務我們cline端需要再專案工程匯入ftp4j-1.7.2.jar包

這邊作個使用的邏輯分析:首先在我們的專案工程FtpApplication中啟動這個OtaService,其中OtaService作為一個服務執行起來,在這個服務裡面拿到封裝好ftp相關介面的DownLoad.java進行ftp檔案操作,關鍵程式碼如下:

public void startDownload() {
    // TODO Auto-generated method stub
    mDownLoad.start();
  }

  public void stopDownload() {
    mDownLoad.stop();
  }

  public void cancel() {
    mDownLoad.cancel();
  }

  public String getOldDate() {
    return mDownLoad.getDatabaseOldDate();
  }

  public String getOldVersion() {
    return mDownLoad.getDatabaseOldVersion();
  }

  public void checkVer(String serverRoot) {
    // TODO Auto-generated method stub
    mDownLoad = DownLoad.getInstance();
    mDownLoad.setServeRoot(serverRoot);
    mDownLoad.setFtpInfo(mApp.mFtpInfo);
    mDownLoad.checkUpgrade();
  }

FTPToolkit.java

package com.asir.ota.ftp;

import it.sauronsoftware.ftp4j.FTPClient; 
import it.sauronsoftware.ftp4j.FTPFile;

import java.io.File;
import java.util.List;

import com.asir.ota.clinet.PathToolkit;
import com.asir.ota.ftp.DownLoad.MyFtpListener;

/**
 * FTP客戶端工具
 * 
 */
public final class FTPToolkit {

  private FTPToolkit() {
  }

  /**
   * 建立FTP連線
   * 
   * @param host
   *      主機名或IP
   * @param port
   *      ftp埠
   * @param username
   *      ftp使用者名稱
   * @param password
   *      ftp密碼
   * @return 一個客戶端
   * @throws Exception 
   */
  public static FTPClient makeFtpConnection(String host,int port,String username,String password) throws Exception {
    FTPClient client = new FTPClient();
    try {
      client.connect(host,port);
      if(username != null && password != null) {
        client.login(username,password);
      }
    } catch (Exception e) {
      throw new Exception(e);
    }
    return client;
  }
/**
   * FTP下載檔案到本地一個資料夾,如果本地資料夾不存在,則建立必要的目錄結構
   * 
   * @param client
   *      FTP客戶端
   * @param remoteFileName
   *      FTP檔案
   * @param localPath
   *      存的本地檔案路徑或目錄
   * @throws Exception 
   */
  public static void download(FTPClient client,String remoteFileName,String localPath,long startPoint,MyFtpListener listener) throws Exception {

    String localfilepath = localPath;
    int x = isExist(client,remoteFileName);
    File localFile = new File(localPath);
    if (localFile.isDirectory()) {
      if (!localFile.exists())
        localFile.mkdirs();
      localfilepath = PathToolkit.formatPath4File(localPath
          + File.separator + new File(remoteFileName).getName());
    }

    if (x == FTPFile.TYPE_FILE) {
      try {
        if (listener != null)
          client.download(remoteFileName,new File(localfilepath),startPoint,listener);
        else
          client.download(remoteFileName,startPoint);
      } catch (Exception e) {
        throw new Exception(e);
      }
    } else {
      throw new Exception("the target " + remoteFileName + "not exist");
    }
  }
/**
   * FTP上傳本地檔案到FTP的一個目錄下
   * 
   * @param client
   *      FTP客戶端
   * @param localfile
   *      本地檔案
   * @param remoteFolderPath
   *      FTP上傳目錄
   * @throws Exception 
   */
  public static void upload(FTPClient client,File localfile,String remoteFolderPath,MyFtpListener listener) throws Exception {
    remoteFolderPath = PathToolkit.formatPath4FTP(remoteFolderPath);
    try {
      client.changeDirectory(remoteFolderPath);
      if (!localfile.exists())
        throw new Exception("the upload FTP file"
            + localfile.getPath() + "not exist!");
      if (!localfile.isFile())
        throw new Exception("the upload FTP file"
            + localfile.getPath() + "is a folder!");
      if (listener != null)
        client.upload(localfile,listener);
      else
        client.upload(localfile);
      client.changeDirectory("/");
    } catch (Exception e) {
      throw new Exception(e);
    }
  }

/**
   * FTP上傳本地檔案到FTP的一個目錄下
   * 
   * @param client
   *      FTP客戶端
   * @param localfilepath
   *      本地檔案路徑
   * @param remoteFolderPath
   *      FTP上傳目錄
   * @throws Exception 
   */
  public static void upload(FTPClient client,String localfilepath,MyFtpListener listener) throws Exception {
    File localfile = new File(localfilepath);
    upload(client,localfile,remoteFolderPath,listener);
  }

/**
   * 批量上傳本地檔案到FTP指定目錄上
   * 
   * @param client
   *      FTP客戶端
   * @param localFilePaths
   *      本地檔案路徑列表
   * @param remoteFolderPath
   *      FTP上傳目錄
   * @throws Exception 
   */
  public static void uploadListPath(FTPClient client,List<String> localFilePaths,MyFtpListener listener) throws Exception {
    remoteFolderPath = PathToolkit.formatPath4FTP(remoteFolderPath);
    try {
      client.changeDirectory(remoteFolderPath);
      for (String path : localFilePaths) {
        File file = new File(path);
        if (!file.exists())
          throw new Exception("the upload FTP file" + path + "not exist!");
        if (!file.isFile())
          throw new Exception("the upload FTP file" + path
              + "is a folder!");
        if (listener != null)
          client.upload(file,listener);
        else
          client.upload(file);
      }
      client.changeDirectory("/");
    } catch (Exception e) {
      throw new Exception(e);
    }
  }
/**
   * 批量上傳本地檔案到FTP指定目錄上
   * 
   * @param client
   *      FTP客戶端
   * @param localFiles
   *      本地檔案列表
   * @param remoteFolderPath
   *      FTP上傳目錄
   * @throws Exception 
   */
  public static void uploadListFile(FTPClient client,List<File> localFiles,MyFtpListener listener) throws Exception {
    try {
      client.changeDirectory(remoteFolderPath);
      remoteFolderPath = PathToolkit.formatPath4FTP(remoteFolderPath);
      for (File file : localFiles) {
        if (!file.exists())
          throw new Exception("the upload FTP file" + file.getPath()
              + "not exist!");
        if (!file.isFile())
          throw new Exception("the upload FTP file" + file.getPath()
              + "is a folder!");
        if (listener != null)
          client.upload(file,listener);
        else
          client.upload(file);
      }
      client.changeDirectory("/");
    } catch (Exception e) {
      throw new Exception(e);
    }
  }
/**
   * 判斷一個FTP路徑是否存在,如果存在返回型別(FTPFile.TYPE_DIRECTORY=1、FTPFile.TYPE_FILE=0、
   * FTPFile.TYPE_LINK=2) 如果檔案不存在,則返回一個-1
   * 
   * @param client
   *      FTP客戶端
   * @param remotePath
   *      FTP檔案或資料夾路徑
   * @return 存在時候返回型別值(檔案0,資料夾1,連線2),不存在則返回-1
   */
  public static int isExist(FTPClient client,String remotePath) {
    remotePath = PathToolkit.formatPath4FTP(remotePath);
    FTPFile[] list = null;
    try {
      list = client.list(remotePath);
    } catch (Exception e) {
      return -1;
    }
    if (list.length > 1)
      return FTPFile.TYPE_DIRECTORY;
    else if (list.length == 1) {
      FTPFile f = list[0];
      if (f.getType() == FTPFile.TYPE_DIRECTORY)
        return FTPFile.TYPE_DIRECTORY;
      // 假設推理判斷
      String _path = remotePath + "/" + f.getName();
      try {
        int y = client.list(_path).length;
        if (y == 1)
          return FTPFile.TYPE_DIRECTORY;
        else
          return FTPFile.TYPE_FILE;
      } catch (Exception e) {
        return FTPFile.TYPE_FILE;
      }
    } else {
      try {
        client.changeDirectory(remotePath);
        return FTPFile.TYPE_DIRECTORY;
      } catch (Exception e) {
        return -1;
      }
    }
  }
public static long getFileLength(FTPClient client,String remotePath) throws Exception {
    String remoteFormatPath = PathToolkit.formatPath4FTP(remotePath);
    if(isExist(client,remotePath) == 0) {
      FTPFile[] files = client.list(remoteFormatPath);
      return files[0].getSize();

    }else {
      throw new Exception("get remote file length error!");
    }
  }

  /**
   * 關閉FTP連線,關閉時候像伺服器傳送一條關閉命令
   * 
   * @param client
   *      FTP客戶端
   * @return 關閉成功,或者連結已斷開,或者連結為null時候返回true,通過兩次關閉都失敗時候返回false
   */

  public static boolean closeConnection(FTPClient client) {
    if (client == null)
      return true;
    if (client.isConnected()) {
      try {
        client.disconnect(true);
        return true;
      } catch (Exception e) {
        try {
          client.disconnect(false);
        } catch (Exception e1) {
          e1.printStackTrace();
          return false;
        }
      }
    }
    return true;
  }
}

包括登入,開始下載,取消下載,獲取升級檔案版本號和伺服器版本校驗等。其它的是一些資料庫,SD卡檔案相關操作,那麼最後在我們下載完成之後需要對檔案進行一個檔案解壓再執行升級操作,這部分在ZipExtractor.java和OTAProvider.java中實現

示例程式碼點選下載

總結

到此這篇關於Android使用ftp方式實現檔案上傳和下載的文章就介紹到這了,更多相關android ftp檔案上傳下載內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!