Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 檔案儲存實作:寫入內部儲存空間並讀回內容

編輯:關於 Android 程式設計

Android 的檔案存取圍繞著 Context 的 openFileOutput 與 openFileInput 展開,位置固定在 /data/data/<package name>/files/。本文以「輸入檔名與內容、按鈕存檔」為例,把寫入與讀取兩個方向都走完。

版面與 Activity

畫面上放兩個輸入框(檔名、內容)與一個保存按鈕,點擊時把值取出交給 service 層處理:

public class FileActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button button = (Button) this.findViewById(R.id.button);
        button.setOnClickListener(new ButtonClickListener());
    }

    private final class ButtonClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            EditText filenameText = (EditText) findViewById(R.id.filename);
            EditText contentText  = (EditText) findViewById(R.id.filecontent);

            String filename = filenameText.getText().toString();
            String content  = contentText.getText().toString();

            FileService service = new FileService(getApplicationContext());
            // 傳 getApplicationContext() 或 this 皆可,Activity 本身也是 Context

            try {
                service.save(filename, content);
                Toast.makeText(getApplicationContext(), R.string.success, 1).show();
            } catch (Exception e) {
                Toast.makeText(getApplicationContext(), R.string.fail, 1).show();
                e.printStackTrace();
            }
        }
    }
}

Service 層:寫入

public class FileService {
    private Context context;

    public FileService(Context context) { this.context = context; }

    public void save(String filename, String content) throws Exception {
        FileOutputStream outStream =
                context.openFileOutput(filename, Context.MODE_PRIVATE);
        outStream.write(content.getBytes());
        outStream.close();          // 一定要關,否則內容可能沒落地
    }
}

openFileOutput 的第一個參數是檔名,不可包含路徑分隔符「/」;檔案不存在時 Android 會自動建立,位置在 /data/data/<package name>/files/。想看實際檔案,可在 Eclipse 中開啟 File Explorer 視圖(Window → Show View → Other → Android → File Explorer),展開該目錄即可。

content.getBytes() 使用系統預設字元編碼,在 Android 上就是 UTF-8,所有字串都能正確編碼;若不指定而系統無預設編碼,則會退回 ISO-8859-1。跨語言情境下建議明確寫成 getBytes("UTF-8")。

四種操作模式

  • Context.MODE_PRIVATE = 0:預設值。檔案私有,僅本應用可存取;寫入時覆蓋原內容。
  • Context.MODE_APPEND = 32768:檢查檔案是否存在,存在則追加內容,否則新建。
  • Context.MODE_WORLD_READABLE = 1:允許其他應用讀取。
  • Context.MODE_WORLD_WRITEABLE = 2:允許其他應用寫入。

若確實要讓其他應用讀寫,可將旗標相加傳入:

openFileOutput("itcast.txt",
        Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);

但這兩個模式在後續 Android 版本中已被弱化或移除,正是因為它繞過了 Android 的安全模型。跨應用分享檔案的正確做法是用 FileProvider 搭配內容 URI 並授予臨時權限。

為什麼預設是私有的

Android 有一套自己的安全模型:應用程式(apk)安裝時,系統會為它分配一個 userid。當該應用要存取檔案等資源時,需要 userid 相符。因此任何應用建立的檔案、SharedPreferences、資料庫預設都是私有的,位於 /data/data/<package name>/ 下,其他程式無法存取——除非建立時明確指定了 WORLD_READABLE 或 WORLD_WRITEABLE。理解這一點,就不會把「讀不到別人的檔案」誤判為 bug。

讀取內容

在 FileService 中補上讀取方法,用輸入流逐段讀進記憶體再轉為字串:

public String read(String filename) throws Exception {
    FileInputStream inputStream = context.openFileInput(filename);
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

    byte[] buffer = new byte[1024];
    int len = 0;
    // read() 回傳 -1 代表讀完;否則回傳本次實際讀到的位元組數
    while ((len = inputStream.read(buffer)) != -1) {
        outputStream.write(buffer, 0, len);
    }
    inputStream.close();

    return new String(outputStream.toByteArray());
}

這裡有個常見錯誤值得強調:inputStream.read(buffer) 只讀「滿一個陣列」或到檔尾為止,並不保證一次讀完。因此必須放在迴圈裡反覆呼叫,直到回傳 -1。少了迴圈,大檔案就會被截斷。

寫測試類驗證

用 AndroidTestCase 寫一個簡單的讀取測試:

public class readTest extends AndroidTestCase {
    private static final String TAG = "FileServiceTest";

    public void testRead() throws Exception {
        FileService service = new FileService(this.getContext());
        String result = service.read("lidewei.txt");
        Log.i(TAG, result);
    }
}

同時要在 AndroidManifest.xml 中掛上測試用的 instrumentation 與 test runner 函式庫:

<uses-library android:name="android.test.runner" />

<instrumentation
    android:name="android.test.InstrumentationTestRunner"
    android:targetPackage="com.credream.file" />

完成後對測試類按右鍵執行,並用 logcat 的過濾器只看 FileServiceTest 這個 tag,就能確認檔案內容是否如預期讀出。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved