Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 檔案與 Base64 互轉實作:encode 與 decode 兩個工具方法

編輯:關於 Android 程式設計

專案裡遇到要傳檔案時,最省事的做法是把檔案轉成 Base64 字串再送出去,收端再把字串解回位元組寫存檔案。這個方式邏輯簡單、不用處理二進位流的種種細節,但代價也很明確:不適合太大的檔案,因為整個檔案要一次讀進記憶體,檔案一大就會有效率與 OOM 的風險。

至於「多大算太大」,這跟裝置可用記憶體、讀取方式都有關係,建議依實機情境自行實測評估。以下提供一組可直接複用的方法。

一、引入 Base64 類別

Android 2.2 之後內建了 android.util.Base64,不必再自己找第三方實作:

import android.util.Base64;

二、檔案轉 Base64 字串

思路是:開啟檔案 → 依檔案大小配置位元組陣列 → 一次讀入 → 編碼成字串。

/**
 * 將檔案轉成 Base64 字串
 * @param path 檔案路徑
 * @return Base64 編碼後的字串
 */
public static String encodeBase64File(String path) throws Exception {
    File file = new File(path);
    FileInputStream inputFile = new FileInputStream(file);
    byte[] buffer = new byte[(int) file.length()];
    inputFile.read(buffer);
    inputFile.close();
    return Base64.encodeToString(buffer, Base64.DEFAULT);
}

這裡用 (int) file.length() 直接依檔案大小開好剛好的陣列,寫法簡潔,但這也是「不適合大檔」的根本原因——檔案多大,記憶體就要一次吃掉多少。

三、Base64 字串還原成檔案

/**
 * 將 Base64 字串解碼並存檔
 * @param base64Code 編碼後的字串
 * @param savePath   檔案存放路徑
 */
public static void decoderBase64File(String base64Code, String savePath)
        throws Exception {
    byte[] buffer = Base64.decode(base64Code, Base64.DEFAULT);
    FileOutputStream out = new FileOutputStream(savePath);
    out.write(buffer);
    out.close();
}

解碼端反過來做即可:解碼成位元組陣列,再整批寫入檔案。

四、實務上的幾點提醒

  • 編碼參數:Base64.DEFAULT 是最通用的選擇;若要放進 URL 或做為檔名的一部分,可改用 Base64.NO_WRAP 或 Base64.URL_SAFE,避免換行與特殊字元惹麻煩。
  • 檔案大小:Base64 會讓資料量增加約三分之一,加上一次整檔進記憶體,傳大檔請改用分塊串流上傳。
  • IO 收尾:範例為求簡潔直接 close,正式專案建議用 try-with-resources 或 finally 確保串流一定被關掉。
  • 讀取完整性:inputFile.read(buffer) 不保證一次讀滿,嚴謹的寫法應該檢查回傳值或改用迴圈讀到 EOF。

整體來說,Base64 互轉適合用在小型憑證、設定檔、小圖示這類場合;一旦是影音或大圖,還是本分地走串流上傳才對。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved