編輯:關於 Android 程式設計
Android 為開發者準備了多種數據存儲方式,包括 ContentProvider、文件存儲、SharedPreferences、SQLite 數據庫以及網絡存儲。本文聚焦其中的文件存儲,從操作模式講到內部私有文件、SD 卡讀寫,再到 assets 資源的訪問,並附上可複用的 IO 工具類。
由於 Android 基於 Linux,讀寫文件時需要明確指定操作模式,這一點與傳統 Java 略有不同。

Context 類封裝了 openFileInput(String name) 與 openFileOutput(String name, int mode) 兩個方法,前者獲取輸入流,後者獲取輸出流。常用的模式有:
1. MODE_PRIVATE:默認模式,文件為私有,僅應用自身可訪問,寫入會覆蓋原內容。
2. MODE_APPEND:文件存在則追加內容,否則新建。
3. MODE_WORLD_READABLE:允許其他應用讀取。
4. MODE_WORLD_WRITEABLE:允許其他應用寫入。
此外還有幾個實用方法:getDir() 獲取或創建子目錄、getFilesDir() 獲取 data 目錄絕對路徑、fileList() 列出 data 目錄下所有文件、deleteFile() 刪除指定文件。
布局代碼:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="16dp"> <EditText android:id="@+id/ed_file_save" android:layout_width="match_parent" android:layout_height="wrap_content" /> <Button android:id="@+id/btn_file_save" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:text="保存內容" /> <Button android:id="@+id/btn_file_read" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:text="讀取內容" /> <TextView android:id="@+id/tv_read_file" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:textColor="#000" android:textSize="14sp" /> </LinearLayout>
Activity 代碼:
package com.example.datasave; import android.content.Context; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class FileDataActivity extends AppCompatActivity { private EditText ed_file_save; private Button btn_file_save; private Button btn_file_read; private TextView tv_read_file; private String fileName = "hello.txt"; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_file); ed_file_save = (EditText) findViewById(R.id.ed_file_save); btn_file_save = (Button) findViewById(R.id.btn_file_save); btn_file_read = (Button) findViewById(R.id.btn_file_read); tv_read_file = (TextView) findViewById(R.id.tv_read_file); btn_file_save.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String fileContent = ed_file_save.getText().toString(); try { save(fileContent); ToastUtils.showToast(FileDataActivity.this, "文件寫入成功"); } catch (Exception e) { e.printStackTrace(); ToastUtils.showToast(FileDataActivity.this, "文件寫入失敗"); } } }); btn_file_read.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { try { String content = read(); tv_read_file.setText("文件的內容是:" + content); } catch (IOException e) { e.printStackTrace(); ToastUtils.showToast(FileDataActivity.this, "讀取文件失敗!"); } } }); } public void save(String fileContent) throws Exception { FileOutputStream output = this.openFileOutput(fileName, Context.MODE_PRIVATE); output.write(fileContent.getBytes()); output.close(); } public String read() throws IOException { FileInputStream input = this.openFileInput(fileName); byte[] temp = new byte[1024]; StringBuffer stringBuffer = new StringBuffer(""); int len = 0; while ((len = input.read(temp)) > 0) { stringBuffer.append(new String(temp, 0, len)); } input.close(); return stringBuffer.toString(); } }
這裡採用私有模式,數據僅本應用可讀且會覆蓋舊內容,適合存放簡單的鍵值型文本。

操作 SD 卡需要申請相應權限:
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
由於不少機型並沒有可拆卸的 SD 卡,讀寫前務必判斷存儲是否已掛載。核心邏輯如下:
public void save2SDCard(String content) throws Exception { if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { String fileName3 = Environment.getExternalStorageDirectory().getCanonicalPath() + File.separator + "test" + File.separator + fileName2; File file = new File(fileName3); if (!file.getParentFile().exists()) { file.getParentFile().mkdir(); } FileOutputStream fileOutputStream = new FileOutputStream(file); fileOutputStream.write(content.getBytes()); fileOutputStream.close(); } else { ToastUtils.showToast(this, "SDCard不存在"); } } public String readFromSD() throws Exception { StringBuffer stringBuffer = new StringBuffer(""); if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { String fileName3 = Environment.getExternalStorageDirectory().getCanonicalPath() + File.separator + "test" + File.separator + fileName2; File file = new File(fileName3); if (!file.getParentFile().exists()) { file.getParentFile().mkdir(); } FileInputStream fileInputStream = new FileInputStream(file); byte[] temp = new byte[1024]; int len = 0; while ((len = fileInputStream.read(temp)) > 0) { stringBuffer.append(new String(temp, 0, len)); } fileInputStream.close(); } else { ToastUtils.showToast(this, "SDCard不存在"); } return stringBuffer.toString(); }

res/raw 下的文件會被映射進 R 文件,可直接通過資源 ID 訪問。assets 則不會被映射,它支持目錄結構,需借助 AssetManager 打開:
AssetManager assetsManager = getAssets(); InputStream inputStream = assetsManager.open("fileName");
把常用的讀寫邏輯沉澱成工具類,能讓業務代碼更清爽:
package com.example.datasave.io; import android.content.Context; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; public class IOUtils { public static void write(String filePath, String content, boolean append) { BufferedWriter bufw = null; try { bufw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath, append))); bufw.write(content); } catch (Exception e1) { e1.printStackTrace(); } finally { if (bufw != null) { try { bufw.close(); } catch (IOException e) { e.printStackTrace(); } } } } public static String read(String path) { BufferedReader bufr = null; try { bufr = new BufferedReader(new InputStreamReader(new FileInputStream(path))); StringBuffer sb = new StringBuffer(); String str = null; while ((str = bufr.readLine()) != null) { sb.append(str); } return sb.toString(); } catch (Exception e) { e.printStackTrace(); } finally { if (bufr != null) { try { bufr.close(); } catch (IOException e) { e.printStackTrace(); } } } return null; } public static String read(InputStream is) { BufferedReader bufr = null; try { bufr = new BufferedReader(new InputStreamReader(is)); StringBuffer sb = new StringBuffer(); String str = null; while ((str = bufr.readLine()) != null) { sb.append(str); } return sb.toString(); } catch (Exception e) { e.printStackTrace(); } finally { if (bufr != null) { try { bufr.close(); } catch (IOException e) { e.printStackTrace(); } } } return null; } public static byte[] readBytes(Context context, String fileName) { FileInputStream fin = null; byte[] buffer = null; try { fin = context.openFileInput(fileName); int length = fin.available(); buffer = new byte[length]; fin.read(buffer); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (fin != null) { fin.close(); fin = null; } } catch (IOException e) { e.printStackTrace(); } } return buffer; } public static String read(Context context, String filename) throws IOException { FileInputStream inStream = context.openFileInput(filename); ByteArrayOutputStream outStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while ((len = inStream.read(buffer)) != -1) { outStream.write(buffer, 0, len); } byte[] data = outStream.toByteArray(); return new String(data); } }
至此,Android 的文件存儲與讀寫就梳理完了。若在實踐中遇到疑問或發現疏漏,歡迎交流指正。
Android Camera 預覽過程的資料流解析
硬件平台:Atmel SAMA5D3 SoC + OV2640 Camera Sensor;Android 版本:4.2.2。 mediaserver 進程是 Camer
用 JNI 與 inotify 實作 App 自我卸載偵測
前言 這個需求在一般專案中幾乎遇不到,只有少數特殊場景才會需要。問題在於 Android 的 Java 層並沒有提供「監聽自身被移除」的接口,因此只能往 Native 層
Android 中 ShareSDK 社會化分享功能實戰教程
前言:最近參與的專案用到了社會化分享功能,由於此前從未接觸過這類需求,我便一邊查閱資料、一邊在專案裡摸索實作,慢慢理清了頭緒。這篇文章算是自己對 ShareSDK 的學習
自定義 ViewGroup 實作教學:打造會自動換行的標籤容器 LineBreakLayout
前陣子工作比較滿檔,部落格停更了一段時間,剛把手邊的專案收尾,就趕緊回來替自定義控制項系列補上一篇。這次要動手做的是「標籤自動換行」的版面容器——剛好之前有個案子用得到,