編輯:Android 開發實例
Android 為開發者準備了五種數據存儲途徑,選對場景比寫對代碼更重要。本文先給出全景,再重點演示最直觀的一種——文件存儲。
1. SharedPreferences:以 key-value 形式存儲,底層就是 XML 文件。適合存放配置項、標誌位等零散的小數據。
2. 文件存儲:直接讀寫文件,分內部私有存儲與外部存儲。適合文本、緩存、導出的數據。
3. SQLite 數據庫:結構化數據的首選,支持 SQL 查詢、事務與索引。
4. ContentProvider:不是存儲方式本身,而是「對外暴露數據」的標準接口,通訊錄、媒體庫都通過它訪問。
5. 網絡存儲:把數據放到服務端,適合需要跨設備同步或數據量大的場景。
本文聚焦第二種。Android 的文件操作本質上就是 Java 的 FileOutputStream 和 FileInputStream,只是 Activity 提供了 openFileOutput / openFileInput 這兩個便捷方法,會自動把路徑解析到應用的私有目錄。
三步走:拿到輸出流、寫入字節、刷新並關閉。
FileOutputStream foStream = openFileOutput(fileName, MODE_PRIVATE); // fileName:要寫入的文件名 // MODE_PRIVATE:默認模式,文件私有僅本應用可訪問,內容會覆蓋原文件 // MODE_APPEND:文件存在則追加,不存在則新建 // MODE_WORLD_READABLE / MODE_WORLD_WRITEABLE: // 允許其他應用讀/寫,因安全問題已在 API 17 後廢棄,不建議使用 byte[] buffer = fileContent.getBytes(); foStream.write(buffer); Toast.makeText(MainActivity.this, "寫入成功", Toast.LENGTH_SHORT).show(); foStream.flush(); // 刷新寫出流,確保數據真正落盤 foStream.close();
FileInputStream fiStream = openFileInput(fileName); int len = fiStream.available(); // 拿到可用字節數 byte[] buffer = new byte[len]; fiStream.read(buffer); etContent.setText(new String(buffer)); Toast.makeText(MainActivity.this, "讀取成功", Toast.LENGTH_SHORT).show(); fiStream.close();
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class MainActivity extends AppCompatActivity {
private EditText etName;
private EditText etContent;
private Button btnWrite;
private Button btnRead;
private String fileName = "";
private String fileContent = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etName = (EditText) findViewById(R.id.etName);
etContent = (EditText) findViewById(R.id.etContent);
btnWrite = (Button) findViewById(R.id.btnWrite);
btnRead = (Button) findViewById(R.id.btnRead);
btnWrite.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
fileName = etName.getText().toString();
fileContent = etContent.getText().toString();
try {
FileOutputStream foStream = openFileOutput(fileName, MODE_PRIVATE);
byte[] buffer = fileContent.getBytes();
foStream.write(buffer);
Toast.makeText(MainActivity.this, "寫入成功", Toast.LENGTH_SHORT).show();
foStream.flush();
foStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
});
btnRead.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
fileName = etName.getText().toString();
try {
FileInputStream fiStream = openFileInput(fileName);
int len = fiStream.available();
byte[] buffer = new byte[len];
fiStream.read(buffer);
etContent.setText(new String(buffer));
Toast.makeText(MainActivity.this, "讀取成功", Toast.LENGTH_SHORT).show();
fiStream.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"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/etName"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:text="文件名" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/etContent"
android:layout_below="@+id/etName"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:text="文件內容" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="保存"
android:id="@+id/btnWrite"
android:layout_alignTop="@+id/btnRead"
android:layout_toLeftOf="@+id/btnRead"
android:layout_toStartOf="@+id/btnRead" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="讀取"
android:id="@+id/btnRead"
android:layout_below="@+id/etContent"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
1. available() 的返回值不保證等於文件總長度。它返回的是「估計可讀字節數」,對於本地文件通常準確,但這是文檔明確提醒的實現依賴行為。更穩健的讀法是循環 read 直到返回 -1,或使用 ByteArrayOutputStream 拼接。
2. 中文編碼要顯式指定。getBytes() 和 new String() 不帶參數時依賴平台默認編碼,跨設備可能亂碼,建議寫成 getBytes("UTF-8") 和 new String(buffer, "UTF-8")。
3. 文件不存在會拋 FileNotFoundException。示例中用 catch (Exception) 一網打盡,實際項目應該針對性處理,並給用戶明確提示。
4. 存儲位置要選對。openFileOutput 寫的是內部私有存儲(/data/data/包名/files),卸載即清除,用戶不可見;如果需要用戶能通過文件管理器訪問,應該改寫外部存儲並處理 Android 10 的分區存儲與 SAF 框架。
5. 什麼時候別用文件。如果需要按條件查詢、排序、更新部分字段,SQLite 或 Room 遠比「讀全文件、改字符串、寫回去」高效。
Android SQLite 增刪改查實戰:Person 模組逐層拆解
理論看再多,不如把一個完整的小模組從頭寫一遍。以下以「Person(聯絡人)」為例,依 Android 建議的分層方式拆成四個部分:實體類、資料庫 Helper、業務邏輯
Android 解析度、像素、密度、螢幕尺寸與 DPI 的關係與計算
做 Android 介面適配,繞不開這幾個名詞:螢幕尺寸、解析度、密度、DPI、dp。它們彼此相關卻常被混用,一旦搞錯,就會出現「同一張圖在不同機子上大小差很多」的經典問
Android 手機衛士(八):安裝過程中處理回退按鈕的邏輯
在手機衛士先前的版本升級對話框中:有些使用者暫時不想更新,卻沒有點擊「稍後再說」,而是選擇按下回退鍵。此時的邏輯應該是讓使用者進入 home 介面,而不是停留在 spla
Android 應用本地化:多語系字串資源設定
Android App 可能在不同語言與地區運行。本地化可讓文字、數字、日期等更符合當地使用者的習慣。 建立語言資源資料夾 在 res 下建立 values-it、val