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

在 Android 應用自己的目錄下建立檔案

編輯:Android 開發教學

要在 App 的私有目錄裡建立檔案,關鍵是兩個方法:getFilesDir() 取得 files 目錄路徑,getCacheDir() 取得 cache 目錄路徑。兩者都位於 /data/data/<套件名>/ 底下,不需要任何權限。

package com.example.listfile;

import java.io.File;
import java.io.IOException;
import android.app.Activity;
import android.os.Bundle;
import android.os.Process;
import android.widget.TextView;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        int myProcessID = Process.myPid();

        File yygypath = this.getFilesDir();   // this.getCacheDir() 亦可
        String yygypathstr = yygypath.toString();

        File file = new File(yygypath, "yygytest");
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }

        yygypathstr = yygypathstr + " pid is " + myProcessID;
        TextView tv = new TextView(this);
        tv.setText(yygypathstr);
        setContentView(tv);
    }

    public void onDestory() {
        super.onDestroy();
        this.finish();
        android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(0);
    }
}

執行結果

用 adb shell 觀察目錄內容:

root@generic:/data/data/com.example.listfile/files # ll
-rw------- u0_a53   u0_a53          0 2014-04-21 13:38 yygytest
root@generic:/data/data/com.example.listfile/files #

補充兩點:files 目錄適合放必須長期保留的資料,cache 目錄則是給暫存檔用,系統在空間不足時會自行清除,所以不要把唯一一份的重要資料只存在 cache 裡。另外,若日後想把檔案寫到外部儲存空間,才需要加上 WRITE_EXTERNAL_STORAGE 權限。

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