編輯:關於 Android 程式設計
I/O 流是 Android 開發中最容易被寫錯的基本功之一。下面用四個由淺入深的例子把它整理清楚,並先記住三條原則:
InputStream 與 OutputStream 中的「入」與「出」,方向都是相對記憶體而言。讀進記憶體用 InputStream,寫出記憶體用 OutputStream。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),否則最後一筆會帶進多餘的贅位。
取得 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);
}
}
}
把上面串起來,可以歸納出幾條判斷規則:
read() 從不保證一次讀完,一律以迴圈搭配回傳值判斷結束。available() 估算大小;網路串流則必須用 ByteArrayOutputStream 這類可動態擴充的容器逐段累積。finally,所以那裡才是關閉的正確位置。這四點掌握了,Java I/O 的骨架其實就完整了。剩下的差異多半在各個 decorator 的行為上,而那又是另一個主題。
Android 圖像處理:底片(濾鏡)效果的實現原理
底片效果是如何實現的?我們先來看代碼。 // 底片 public static Bitmap Negative(Bitmap bm) { int Width
Android 進階元件(一):ProgressBar、SeekBar、RatingBar 與滾動容器
Android 的進階 UI 元件中,ProgressBar、SeekBar、RatingBar、ScrollView、HorizontalScrollView 與 Au
5555 端口被佔用導致模擬器無法識別的解決方法
「昨天模擬器還好好的,今天 Eclipse 突然就識別不了了。」——這個問題困擾過不少 Android 開發者。排查之後發現,罪魁禍首往往是某個手機助手類軟件:它們為了實
Android 自定義控件實戰:打造可複用的標題導航列並打包共享
幾乎每個 App 都有一條頂部的標題導航列,左邊返回、中間標題、右邊操作按鈕。與其每個專案重寫一次,不如封裝成自定義 View,再打包成 library 給其他專案共用。