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

Android 內部存儲實踐:文件讀寫與 Cache 目錄的使用

編輯:關於 Android 程式設計

Android 的存儲方式有好幾種,內部存儲是最基礎的一種。它的特點是每個應用擁有自己私有的目錄,卸載時相關數據會被系統自動清除,因此適合存放不需要與外部共享的數據。

一、項目結構

二、布局文件

一個輸入框加一個保存按鈕:

<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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="28dp"
        android:layout_marginTop="17dp"
        android:ems="10" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/editText1"
        android:layout_below="@+id/editText1"
        android:layout_marginTop="54dp"
        android:text="保存信息" />
</RelativeLayout>

三、文件操作工具類 FileService

/**
 * 使用內部存儲,應用卸載時相關信息會被清除
 */
public class FileService {

    private Context context;

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

    /**
     * 保存內容到文件
     * @param fileName 文件名
     * @param mode     打開模式
     * @param data     數據緩衝區
     */
    public boolean saveContentToFile(String fileName, int mode, byte[] data) {
        boolean flag = false;
        FileOutputStream outputStream = null;
        try {
            outputStream = context.openFileOutput(fileName, mode);
            outputStream.write(data, 0, data.length);
            flag = true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try { outputStream.close(); } catch (Exception e2) { }
            }
        }
        return flag;
    }

    /** 讀取文件內容 */
    public String readContentFromFile(String fileName) {
        FileInputStream fileInputStream = null;
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            fileInputStream = context.openFileInput(fileName);
            int len = 0;
            byte[] data = new byte[1024];
            while ((len = fileInputStream.read(data)) != -1) {
                outputStream.write(data, 0, len);
            }
            return new String(outputStream.toByteArray());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fileInputStream != null) {
                try { fileInputStream.close(); } catch (IOException e) { }
            }
        }
        return "";
    }

    /** 保存文件到自定義子目錄 */
    public boolean saveCacheFile(String fileName, byte[] data) {
        boolean flag = false;
        File file = context.getFilesDir();
        FileOutputStream outputStream = null;
        try {
            File folderFile = new File(file.getAbsoluteFile() + "/txt");
            if (!folderFile.exists()) {
                folderFile.mkdirs(); // 遞歸創建目錄
            }
            outputStream = new FileOutputStream(folderFile.getAbsolutePath() + "/" + fileName);
            outputStream.write(data, 0, data.length);
            flag = true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try { outputStream.close(); } catch (IOException e) { }
            }
        }
        return flag;
    }

    /** 列出目錄下的所有文件絕對路徑 */
    public void listCacheFile() {
        File file = context.getFilesDir();
        File root = new File(file.getAbsoluteFile() + "/txt");
        File[] listFiles = root.listFiles();
        if (listFiles == null) return;
        for (File file2 : listFiles) {
            System.err.println("--->>" + file2.getAbsolutePath());
        }
    }
}

四、MainActivity

public class MainActivity extends Activity {

    private Button button;
    private EditText editText;
    private FileService fileService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button = (Button) this.findViewById(R.id.button1);
        editText = (EditText) this.findViewById(R.id.editText1);
        fileService = new FileService(this);

        button.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                String valueString = editText.getText().toString().trim();
                boolean flag = fileService.saveContentToFile(
                        "bb.txt", Context.MODE_APPEND, valueString.getBytes());
                if (flag) {
                    Toast.makeText(MainActivity.this, "保存成功!", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

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

五、測試類

public class MyTest extends AndroidTestCase {

    private static final String TAG = "MyTest";

    /** 保存數據 */
    public void save() {
        FileService fileService = new FileService(getContext());
        boolean flag = fileService.saveContentToFile("aa.txt", Context.MODE_APPEND, "nihao".getBytes());
        Log.i(TAG, "--->>" + flag);
    }

    /** 讀取數據 */
    public void read() {
        FileService fileService = new FileService(getContext());
        String msg = fileService.readContentFromFile("bb.txt");
        Log.i(TAG, "--->>" + msg);
    }

    /** 寫入子目錄 */
    public void testChaceFile() {
        FileService fileService = new FileService(getContext());
        fileService.saveCacheFile("hello.txt", "hello world!".getBytes());
    }

    /** 列出子目錄文件 */
    public void testListFile() {
        FileService fileService = new FileService(getContext());
        fileService.listCacheFile();
    }
}

保存成功後,可以在 data/data/包名/files 目錄下找到對應文件(需要 root 或用 run-as 才能訪問)。

六、幾個實踐要點

1、openFileOutput 的模式參數:MODE_PRIVATE 會覆蓋原文件,MODE_APPEND 則追加寫入。示例裡用了 MODE_APPEND,所以多次點擊按鈕內容會不斷累加。

2、files 與 cache 的區別:getFilesDir() 下的文件是持久的,系統不會主動清理;getCacheDir() 下的文件在內存不足時可能被系統刪除,適合放臨時數據。原始文章示例把方法命名為 saveCacheFile 但實際寫到了 files/txt 目錄,這裡提醒一下,真正想用緩存目錄應改為 context.getCacheDir()。

3、內部存儲不需要讀寫權限,這是它相對外部存儲的一大優勢,不用處理 Android 6.0 以上的動態授權。

4、編碼要顯式指定,new String(bytes) 在目標機與開發機默認編碼不一致時會出現亂碼,正式代碼建議寫成 new String(bytes, "UTF-8")。

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