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

Android 隨手記:byte 陣列、String 與 InputStream 之間的互相轉換

編輯:關於 Android 程式設計

處理網路回應、檔案內容與字串時,這三種型別幾乎天天遇到。把常用的轉換收攏成一個工具類,可以省下不少重複程式碼。

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class InputStreamUtils {

    final static int BUFFER_SIZE = 4096;

    /** InputStream 轉 String */
    public static String InputStreamTOString(InputStream in) throws IOException {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] data = new byte[BUFFER_SIZE];
        int count;
        while ((count = in.read(data, 0, BUFFER_SIZE)) != -1) {
            outStream.write(data, 0, count);
        }
        return new String(outStream.toByteArray(), "UTF-8");
    }

    /** String 轉 InputStream */
    public static InputStream StringTOInputStream(String in) throws IOException {
        return new ByteArrayInputStream(in.getBytes("UTF-8"));
    }

    /** InputStream 轉 byte 陣列 */
    public static byte[] InputStreamTOByte(InputStream in) throws IOException {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] data = new byte[BUFFER_SIZE];
        int count;
        while ((count = in.read(data, 0, BUFFER_SIZE)) != -1) {
            outStream.write(data, 0, count);
        }
        return outStream.toByteArray();
    }

    /** byte 陣列轉 InputStream */
    public static InputStream byteTOInputStream(byte[] in) {
        return new ByteArrayInputStream(in);
    }

    /** byte 陣列轉 String */
    public static String byteTOString(byte[] in) throws IOException {
        return new String(in, "UTF-8");
    }
}

幾個實作上的關鍵點

  • 一定要用 count 當作寫入長度。read() 實際讀到的位元組數可能小於緩衝區大小,若無腦寫入整個 data 陣列,尾部會殘留上一輪的舊資料,這是這類程式最常見的 bug。
  • 編碼要明確指定。原始範例使用 ISO-8859-1,那是為了「位元組與字元一一對應」的 byte-safe 轉換場景(例如把二進位內容塞進字串再傳出去)。一般處理中文或 JSON 內容時應改用 UTF-8,並讓編碼名稱成為參數,不要寫死。
  • 不必要的中間轉換。byte 陣列轉 String 直接用 new String(bytes, charset) 即可,繞一圈 ByteArrayInputStream 反而多一次記憶體複製。
  • 記得釋放資源。ByteArrayOutputStream 的 toByteArray() 之後可以 close();若來源是檔案或網路串流,呼叫方應以 try-with-resources 確保關閉。用完把暫存陣列設為 null 這類微調,在現代 ART 的 GC 下意義不大,不必刻意為之。

更簡潔的替代方案

如果專案能使用 Java 8 以上,InputStream 轉位元組可以直接靠 in.readAllBytes() 一行搞定;若已引入 Apache Commons IO,IOUtils.toString(in, charset) 與 IOUtils.toByteArray(in) 更省事,也省去自己驗證邊界條件。

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