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

Android I/O 流梳理:四個從本地到網路的實作範例

編輯:關於 Android 程式設計

I/O 流是 Android 開發中最容易被寫錯的基本功之一。下面用四個由淺入深的例子把它整理清楚,並先記住三條原則:

  1. InputStream 與 OutputStream 中的「入」與「出」,方向都是相對記憶體而言。讀進記憶體用 InputStream,寫出記憶體用 OutputStream。
  2. 務必區分位元組流與字元流。例如圖片這類二進位資料,絕對不能用字元流處理。
  3. 所有流都必須在 finally 中關閉,或改用 Java 7 的 try-with-resources。

範例一:拷貝文字檔

這個例子刻意示範完整的串接鏈:FileInputStream → InputStreamReader → BufferedReader 負責讀,FileOutputStream → OutputStreamWriter → BufferedWriter 負責寫。

private static final String SDCardDir =
        Environment.getExternalStorageDirectory() + File.separator;

/**
 * 利用 I/O 流拷貝文字檔
 */
private void copyTextFile() {
    FileInputStream fileInputStream = null;
    InputStreamReader inputStreamReader = null;
    BufferedReader bufferedReader = null;
    FileOutputStream fileOutputStream = null;
    OutputStreamWriter outputStreamWriter = null;
    BufferedWriter bufferedWriter = null;
    try {
        fileInputStream = new FileInputStream(SDCardDir + "test.txt");
        // 原檔編碼為 GBK,此處需對齊編碼,否則會出現亂碼
        inputStreamReader = new InputStreamReader(fileInputStream, "GBK");
        bufferedReader = new BufferedReader(inputStreamReader);

        fileOutputStream = new FileOutputStream(SDCardDir + "eeee.txt");
        outputStreamWriter = new OutputStreamWriter(fileOutputStream);
        bufferedWriter = new BufferedWriter(outputStreamWriter);

        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            bufferedWriter.write(line);
            bufferedWriter.newLine();
            bufferedWriter.flush();
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (null != bufferedWriter) bufferedWriter.close();
            if (null != bufferedReader) bufferedReader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

重點是編碼。字元流會經過編碼轉換,讀寫兩端的編碼必須一致,這也是文字檔亂碼最常見的原因。

範例二:拷貝本地圖片

二進位資料不需要編碼轉換,直接之位元組流對拷即可。實務上會用一個緩衝區反覆搬運,而不是一次讀完整個檔:

/**
 * 利用 I/O 流拷貝本地圖片
 */
private void copyImage() {
    FileInputStream fileInputStream = null;
    FileOutputStream fileOutputStream = null;
    try {
        fileInputStream = new FileInputStream(SDCardDir + "beauty.jpg");
        fileOutputStream = new FileOutputStream(SDCardDir + "yyyy.jpg");
        int len = 0;
        byte[] buffer = new byte[1024 * 2];
        while ((len = fileInputStream.read(buffer)) != -1) {
            fileOutputStream.write(buffer, 0, len);
            fileOutputStream.flush();
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (null != fileInputStream) fileInputStream.close();
            if (null != fileOutputStream) fileOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

注意 read() 的回傳值是「實際讀到的位元組數」,寫入時必須用 write(buffer, 0, len) 而非 write(buffer),否則最後一筆會帶進多餘的贅位。

範例三:載入本地圖片並解碼為 Bitmap

取得 FileInputStream 之後,系統 API BitmapFactory.decodeStream(fileInputStream) 就能直接拿到 Bitmap。這裡改用另一條路,順便說明緩衝大小的決定方式。

/**
 * 利用 I/O 流載入本地圖片
 *
 * 注意 buffer 大小的指定方式:
 * byte[] buffer = new byte[fileInputStream.available()];
 *
 * available() 的說明是「回傳可不受阻塞地讀取之位元組數」。
 * 本例圖片位於本地,可不受阻塞讀取,因此可用它取得檔案大小;
 * 但這只適用於本地檔案,網路串流請勿沿用(見範例四)。
 */
private void loadLocalImage() {
    FileInputStream fileInputStream = null;
    try {
        fileInputStream = new FileInputStream(SDCardDir + "beauty.jpg");
        byte[] buffer = new byte[fileInputStream.available()];
        fileInputStream.read(buffer);
        Bitmap bitmap = BitmapFactory.decodeByteArray(buffer, 0, buffer.length);
        mImageView.setImageBitmap(bitmap);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (null != fileInputStream) fileInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

這裡有兩個細節值得留意:一是 available() 的回傳值只是「目前可讀的估計量」,並不等於檔案總大小,用它配置緩衝區只適合小檔且來源為本地的情況;二是 read(buffer) 不保證一次讀完,嚴謹的寫法應該檢查回傳的位元組數是否等於 buffer 長度。

範例四:載入網路圖片

圖片來自遠端時,上面那套做法就會出問題。available() 回傳的值遠小於實際圖片大小,因為資料還沒全部送達。正確策略是「反覆讀取、逐段暫存」:

/**
 * 利用 I/O 流載入網路圖片
 *
 * 做法:
 * 1. 不斷把 inputStream 的資料讀進 buffer
 * 2. 每次讀到的內容寫進 ByteArrayOutputStream
 * 3. 讀完後用 toByteArray() 一次取出全部位元組
 * 4. 交給 BitmapFactory.decodeByteArray() 解碼
 *
 * ByteArrayOutputStream 在此扮演「中轉站」:
 * 我們無法一次從串流取得全部資料,於是透過多次讀取累積,
 * 暫存在 ByteArrayOutputStream,最後再整批取出。
 */
private void loadNetworkImage() {
    mAsyncTask = new DownLoaderAsyncTask();
    mAsyncTask.execute("https://avatar.csdn.net/6/6/D/1_lfdfhl.jpg");
}

private class DownLoaderAsyncTask extends AsyncTask<String, Void, Bitmap> {

    @Override
    protected Bitmap doInBackground(String... params) {
        InputStream inputStream = null;
        ByteArrayOutputStream byteArrayOutputStream = null;
        try {
            URL imageUrl = new URL(params[0]);
            HttpURLConnection connection = (HttpURLConnection) imageUrl.openConnection();
            connection.setConnectTimeout(5000);
            connection.setRequestMethod("GET");
            if (connection.getResponseCode() == 200) {
                inputStream = connection.getInputStream();
                byteArrayOutputStream = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int len;
                while ((len = inputStream.read(buffer)) != -1) {
                    byteArrayOutputStream.write(buffer, 0, len);
                }
                byte[] imageData = byteArrayOutputStream.toByteArray();
                return BitmapFactory.decodeByteArray(imageData, 0, imageData.length);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != inputStream) inputStream.close();
                if (null != byteArrayOutputStream) byteArrayOutputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(Bitmap bitmap) {
        super.onPostExecute(bitmap);
        if (null != bitmap) {
            mImageView.setImageBitmap(bitmap);
        }
    }
}

四個範例背後的共同結論

把上面串起來,可以歸納出幾條判斷規則:

  • 選流看資料型別:文字用字元流(Reader/Writer)並明確指定編碼,圖片與其他二進位資料之位元組流(InputStream/OutputStream)。
  • 讀取用迴圈不用僥倖:read() 從不保證一次讀完,一律以迴圈搭配回傳值判斷結束。
  • 來源決定策略:本地檔可以靠 available() 估算大小;網路串流則必須用 ByteArrayOutputStream 這類可動態擴充的容器逐段累積。
  • 關閉要放 finally:串流佔用系統資源,異常路徑同樣會經過 finally,所以那裡才是關閉的正確位置。

這四點掌握了,Java I/O 的骨架其實就完整了。剩下的差異多半在各個 decorator 的行為上,而那又是另一個主題。

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