編輯:關於 Android 程式設計
Android 為開發者準備了幾套資料持久化方案:檔案儲存、SharedPreferences、SQLite 資料庫,另外還可以把資料寫到外接儲存(SD 卡)。其中檔案儲存是最基礎的一種。
檔案儲存最大的特色是「不做任何格式化處理」——你寫入什麼位元組,檔案裡就是什麼內容,因此特別適合存放簡單的文字或二進位資料,例如設定草稿、快取結果、log 檔等。
Context 類別提供了 openFileOutput() 用來寫入檔案,它接受兩個參數:
/data/data/<package>/files/ 這個 App 私有目錄下,其他應用程式無權存取。MODE_PRIVATE 為預設值,同名檔案會被內容覆蓋;MODE_APPEND 則是若檔案已存在就附加內容,不存在才新建。這個方法回傳 FileOutputStream,取得後就能用一般 Java I/O 串流把資料寫進去。讀取則對應 openFileInput(),只接受檔名,回傳 FileInputStream。
建立一個名為 FilePersistenceTest 的專案,先在 activity_main.xml 放一個輸入框:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<EditText
android:id="@+id/edit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="type something here" />
</LinearLayout>
接著在 Activity 被銷毀時把輸入框的內容存起來:
public class MainActivity extends Activity {
private EditText editText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.edit);
}
public void save(String inputText) {
FileOutputStream fileOutputStream = null; // 檔案輸出串流
BufferedWriter bufferedWriter = null; // 字元緩衝串流
try {
fileOutputStream = openFileOutput("datafile", Context.MODE_PRIVATE);
bufferedWriter = new BufferedWriter(new OutputStreamWriter(fileOutputStream));
bufferedWriter.write(inputText);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bufferedWriter != null) {
try {
bufferedWriter.close(); // 關流時會一併把緩衝區刷入檔案
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
@Override
protected void onDestroy() {
super.onDestroy();
save(editText.getText().toString());
}
}
執行後在輸入框打字:

按下 Back 鍵關閉程式,內容就已落地存檔。此時可以開啟 DDMS 的 File Explorer,找到 /data/data/com.jack.filepersistencetest/files/,就會看到名為 datafile 的檔案:
點擊工具列最左側的按鈕把檔案匯出到電腦,用記事本開啟,內容如下:

可以確認輸入框裡的文字確實被保存下來了。
在 onCreate() 中呼叫 load(),把上次存下的字串還原到輸入框,並把游標移到尾端方便繼續輸入:
public String load() {
FileInputStream in = null; // 檔案輸入串流
BufferedReader reader = null; // 字元緩衝串流
StringBuffer content = new StringBuffer();
try {
in = openFileInput("datafile");
reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
content.append(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return content.toString();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.edit);
String inputText = load();
if (!TextUtils.isEmpty(inputText)) {
editText.setText(inputText);
editText.setSelection(inputText.length()); // 游標移到文末
Toast.makeText(this, "還原成功", Toast.LENGTH_SHORT).show();
}
}
TextUtils.isEmpty() 一次就涵蓋兩種空值判斷:傳入的字串為 null 或空字串時都會回傳 true,省下分別判斷的麻煩。
重新執行,效果如下:

檔案儲存不適合保存結構複雜的資料。若需要查詢、排序、關聯式操作,應該改用 SQLite;若只是幾個 key-value 設定,SharedPreferences 更省事;若是大量圖片或需要對其他 App 開放的大檔,則該放進 App 專用的外接目錄 getExternalFilesDir(),並記得在 Android 6.0 以上動態申請寫入權限。更進階的持久化策略,後續再另行整理。
Android 自定義水波紋流量球進度條控制器的實現
本篇帶大家打造一個仿水波紋的流動球進度條控制器,這是 Android 裡相當主流又吸睛的特效,效果高級大氣。以下為完整實現思路與代碼,供大家參考。 先看效果圖: Cir
Android 完全退出應用程式的實作方式
在 Android 中,若要完全退出應用程式,不能只依賴單一 Activity 的 finish。若 App 內有多個 Activity,直接呼叫 killProcess
Android ViewPager 與內部 View 的事件分發機制及輪播圖實作
我們在使用 ViewPager 時常會有這樣的疑問:當手指在螢幕上滑動時,究竟是 ViewPager 在滑動它內部的那一頁 View,還是 ViewPager 在滑動自己
用 PopupWindow 自定義 Android ActionBar Overflow 菜單
為什麼使用 PopupWindow 實作 Overflow當 ActionBar 上的操作按鈕過多時,系統會自動將部分項目收進 Overflow 選單。若想做出更客製化的