編輯:關於 Android 程式設計
Android 常見的資料存儲方式有四種:SharedPreferences、資料庫、SD 卡,以及檔案存儲。日常開發中第四種用得不算多,但偶爾處理快取、log 或簡單的資料持久化時仍然很順手,這篇就寫個範例整理一下。
透過 Context 的 openFileOutput() 可以將資料寫入檔案,預設存儲路徑是:
/data/data/<packageName>/files/
讀取則用 openFileInput()。
這裡有個常被搞混的關鍵點:內部檔案存儲不需要任何權限,這跟寫入 SD 卡是完全不同的兩件事。寫 SD 卡需要 WRITE_EXTERNAL_STORAGE,而 openFileOutput 操作的是應用私有目錄,系統預設就讓你的 App 自由讀寫,其他 App 則無法存取(除非 root)。
package cc.cv;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
/**
* 檔案存儲詳細示例
*
* 可利用 Context 的 openFileOutput() 將資料存儲到檔案中,
* 預設路徑為 /data/data/<packageName>/files/
* 可利用 Context 的 openFileInput() 將資料從檔案中讀出
*/
public class MainActivity extends Activity {
private Button mSaveButton;
private Button mGetButton;
private Context mContext;
private String mFileName;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
init();
}
private void init() {
mContext = this;
mFileName = "testData";
mSaveButton = (Button) findViewById(R.id.saveButton);
mSaveButton.setOnClickListener(new ClickListenerImpl());
mGetButton = (Button) findViewById(R.id.getButton);
mGetButton.setOnClickListener(new ClickListenerImpl());
}
private class ClickListenerImpl implements OnClickListener {
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.saveButton:
saveDataToFile(mContext, mFileName);
break;
case R.id.getButton:
getDataFromFile(mContext, mFileName);
break;
default:
break;
}
}
}
/** 向檔案中保存資料 */
private void saveDataToFile(Context context, String fileName) {
String data = "Hello,All";
FileOutputStream fileOutputStream = null;
OutputStreamWriter outputStreamWriter = null;
BufferedWriter bufferedWriter = null;
try {
fileOutputStream = context.openFileOutput(fileName, Context.MODE_PRIVATE);
outputStreamWriter = new OutputStreamWriter(fileOutputStream);
bufferedWriter = new BufferedWriter(outputStreamWriter);
bufferedWriter.write(data);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (bufferedWriter != null) {
bufferedWriter.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
/** 從檔案中讀取資料 */
private void getDataFromFile(Context context, String fileName) {
FileInputStream fileInputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader bufferedReader = null;
StringBuilder stringBuilder = null;
String line = null;
try {
stringBuilder = new StringBuilder();
fileInputStream = context.openFileInput(fileName);
inputStreamReader = new InputStreamReader(fileInputStream);
bufferedReader = new BufferedReader(inputStreamReader);
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line);
}
System.out.println("--->" + stringBuilder.toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (bufferedReader != null) {
bufferedReader.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="@+id/saveButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="100dp"
android:text="向 File 中保存數據" />
<Button
android:id="@+id/getButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="260dp"
android:text="從 File 中獲取數據" />
</RelativeLayout>
寫入模式:範例使用 Context.MODE_PRIVATE,這是預設值,同名檔案會被覆寫。若想改成追加,可改用 Context.MODE_APPEND;另外還有 MODE_WORLD_READABLE / MODE_WORLD_WRITEABLE,但這兩個從 API 17 起已被標記為 deprecated,在較新版本上呼叫會直接拋出 SecurityException,請勿使用。
流的關閉:範例只在 finally 中關閉最外層的 BufferedWriter / BufferedReader,實際上關閉外層就會連帶關閉內層串接的串流,這樣寫是正確的。正式專案建議改用 try-with-resources 語法,可以省掉所有 null 判斷。
編碼問題:寫入與讀取都沒指定 charset,會依賴系統預設編碼。若要跨裝置穩定,建議明確傳入 "UTF-8",例如 new OutputStreamWriter(fileOutputStream, "UTF-8")。
調試方式:這個私有目錄無法直接用檔案瀏覽器看到,可以用 adb shell run-as <你的套件名> 進入後查看 files/ 目錄,或用 Android Studio 的 Device Explorer。
OSGi ServiceListener實戰:動態監聽服務註冊與變更
前言 在OSGi的世界裡,動態性是最鮮明的特徵之一。Bundle可以在執行期安裝、啟動、停止、更新與移除,而服務也可能隨時被註冊、修改或取消註冊。若應用需要即時感知這些變
Android 仿社群貼子的 SpannableString 解析技巧
在新浪微博、QQ 空間等社群場景中,貼文常包含話題、表情與好友提及。這類內容通常不是單純文字,而是需要局部變色、可點擊或替換成圖片。Android 中常使用 Spanna
安卓手機如何重設便攜式無線基地台密碼
若要知道或重設安卓手機的便攜式無線基地台密碼,可從設定進入。 1. 開啟手機設定。 2. 選擇「無線和網絡」。 3. 進入「綁定與便攜式熱點」。 4. 選擇「便攜
Android 中 List 循環遍歷效能對比:三種寫法的實測分析
在 Android 開發中,只要是列表風格的介面,幾乎都要用 List 來存放資料。當資料量很少時,任何一種循環遍歷方式的整體效能都看不出差別;但當資料量變大時,選對遍歷