Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 開發基礎:內部檔案儲存的讀寫實作

編輯:Android 開發實例

除了偏好設定與資料庫,Android 還提供了最直接的檔案 I/O 方式。Context 的 openFileOutput 與 openFileInput 會自動把檔案放進應用自己的 /data/data/<package>/files/ 目錄,不用自己拼路徑,也不用手動處理權限,是保存純文字資料最省事的做法。

寫入與讀取

下面的例子用兩個按鈕分別負責寫入與讀出,資料格式簡單,一行一筆:

public class MainActivity extends Activity {
    EditText mname, mage;
    TextView mtv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mname = (EditText) findViewById(R.id.editText1);
        mage = (EditText) findViewById(R.id.editText2);
        mtv = (TextView) findViewById(R.id.textView1);
    }

    public void onClick(View v) {
        String name = mname.getText().toString();
        int age = Integer.parseInt(mage.getText().toString());
        String cont = "name=" + name + ",age=" + age + "\n";

        try {
            int id = v.getId();

            // 內部儲存:以附加模式寫入
            if (id == R.id.button1) {
                FileOutputStream fos = this.openFileOutput("mytext.txt",
                        Context.MODE_APPEND);
                fos.write(cont.getBytes());
                fos.close();
                Toast.makeText(this, "寫入完成", 1).show();
            }
            // 讀取
            else if (id == R.id.button2) {
                FileInputStream fis = this.openFileInput("mytext.txt");
                byte[] bytes = new byte[fis.available()];
                fis.read(bytes);
                fis.close();
                String str = new String(bytes);
                mtv.setText(str);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

MODE_APPEND 表示附加在檔案尾端,沒這個旗標就是覆寫。讀取端則是一次把內容讀進位元組陣列再轉字串,資料量小的時候夠用。

讓其他應用存取同一個檔案

應用沙箱預設不允許跨 App 讀檔,需要靠 createPackageContext 取得對方的 Context,並在建立檔案時加上開放權限的旗標。寫入方要記得帶上 MODE_WORLD_READABLE 或 MODE_WORLD_WRITEABLE(同樣地,這組常數在 API 17 之後已不建議使用,新專案請改用 ContentProvider 或 FileProvider)。

讀取方則有三種常見路徑:

public class MainActivity extends Activity {
    TextView mcontent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mcontent = (TextView) findViewById(R.id.textView1);
    }

    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button1:
                try {
                    readRemoteFileByAbslutePath();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case R.id.button2:
                try {
                    WriteRemoteFileByAbslutePath();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            default:
                break;
        }
    }

    /** 以絕對路徑讀取遠端檔案 */
    public void readRemoteFileByAbslutePath() throws Exception {
        String path = "/data/data/com.nanguabing.filedemo/files/mytext.txt";
        FileInputStream fis = new FileInputStream(path);
        byte[] bytes = new byte[fis.available()];
        fis.read(bytes);
        fis.close();
        String str = new String(bytes);
        mcontent.setText(str);
        Log.i("Other", str);
    }

    /** 以絕對路徑寫入遠端檔案 */
    public void WriteRemoteFileByAbslutePath() throws Exception {
        String path = "/data/data/com.nanguabing.filedemo/files/mytext.txt";
        FileOutputStream fos = new FileOutputStream(path, true);
        fos.write("other write! ".getBytes());
        fos.close();
        Log.i("Other", "other write over!");
    }

    /** 透過套件相關的 Context 讀取 */
    public void readRomoteByPackageContext() throws Exception {
        String pname = "com.nanguabing.filedemo";
        Context ctx = this.createPackageContext(pname,
                Context.CONTEXT_IGNORE_SECURITY);
        FileInputStream fis = ctx.openFileInput("mytext.txt");
        byte[] bytes = new byte[fis.available()];
        fis.read(bytes);
        fis.close();
        Log.i("Other", new String(bytes));
    }

    /** 另一種 Context 建立方式 */
    public void readRomoteByPackageContext2() throws Exception {
        String pname = "com.nanguabing.filedemo";
        Context ctx = this.createPackageContext(pname,
                Context.CONTEXT_INCLUDE_CODE);
        FileInputStream fis = ctx.openFileInput("mytext.txt");
        byte[] bytes = new byte[fis.available()];
        fis.read(bytes);
        fis.close();
        Log.i("Other", new String(bytes));
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}

實務提醒

三種讀取方式裡,絕對路徑寫法最脆弱:路徑寫死、需要特殊權限,在近期版本的 Android 上幾乎必然失敗。以 createPackageContext 搭配對方 Context 的做法相對可控,但仍受限於沙箱與權限模型。若目標是穩定地與其他應用交換資料,正確答案始終是 ContentProvider。

另外,new byte[fis.available()] 這種一次讀完的寫法只適合小檔案;檔案可能較大時,請改用固定緩衝區迴圈讀取,避免記憶體爆掉。

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