Android - 数据存储

原文地址:https://developer.android.com/guide/topics/data/data-storage.html#db


1、Using Shared Preferences

2、Using the Internal Storage
  保存应用程序数据,其他应用程序与用户不能获取,应用程序卸载后,系统将删除相关文件

    1)openFileOutput(), return FileOutputStream
    2)write()
    3)close()

  可以在res/raw/目录下放置文件,使用openRawResource(R.raw.<filename>)打开文件(返回InputStream),但是只能读取不能写入;

  可以使用getCacheDir()打开保存临时数据的目录,如果内部存储空间吃紧,系统将删除该目录下文件用于回收存储空间;

    你必须管理这些临时数据文件并保持合理的空间占用(比如1MB),而非依靠系统;


  其它有用的函数:
    getFilesDir()
      Gets the absolute path to the filesystem directory where your internal files are saved.
    getDir()
      Creates (or opens an existing) directory within your internal storage space.
    deleteFile()
      Deletes a file saved on the internal storage.
    fileList()
      Returns an array of files currently saved by your application.

3、Using the External Storage
  所有应用程序都可以访问扩展存储槽上的文件,需要请求权限:READ_EXTERNAL_STORAGE or WRITE_EXTERNAL_STORAGE

  如果你删除了SD卡或者将扩展存储连接上电脑,则它将不可用,使用前需要判断扩展存储槽的状态:Environment.getExternalStorageState()

/* Checks if external storage is available for read and write */
public boolean isExternalStorageWritable() {
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        return true;
    }
    return false;
}

/* Checks if external storage is available to at least read */
public boolean isExternalStorageReadable() {
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state) ||
        Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
        return true;
    }
    return false;
}

  在扩展存储中保存共享数据,比如歌曲、照片、铃声,需要将文件保存在共享目录下的特定子目录中,如 Music/,Pictures/,Ringtones/.

  Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), fileName); 需要参数:子目录类型

  在扩展存储中保存不共享数据,通过调用 getExternalFilesDir() 获取目录:
    

    有些设备会将一部分内部存储充当扩展存储使用,在这些设备下,

    Android 4.3及以下版本, getExternalFilesDir() 只能获取内部存储充当的扩展存储;

    Android 4.4开始,getExternalFilesDir() 可以获取内部存储与扩展存储,将返回File数组,第一个元素为扩展存储目录;

    可以使用 扩展支持库中的 ContextCompat.getExternalFilesDirs()

  [注] 扩展存储中的共享目录是特定于一些系统应用,如照片、铃声管理程序,它们读取内容时会包含这些目录下文件。

  使用扩展存储中用于存储临时数据的目录: getExternalCacheDir(),卸载应用时,该目录下文件自动被删除。

  可以使用 扩展支持库中的 ContextCompat.getExternalCacheDirs()

测试代码:

package com.android.testlifeterm;

import android.os.Bundle;
import android.os.Environment;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.ViewGroup;
import android.widget.TextView;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by Yizhui on 2016/6/26.
 */
public class DataStorageActivity extends AppCompatActivity {

    private static final String TAG = "DataStorageActivity";

    private TextView mTextView;

    private StringBuilder mStringBuilder = new StringBuilder();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mTextView = new TextView(this);
        addContentView(mTextView, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

        FileOutputStream out = null;
        try {
            out = openFileOutput("citys", MODE_PRIVATE);
            out.write("FZ,BJ,TJ".getBytes());

        } catch (FileNotFoundException e) {
            Log.d(TAG, "openFileOutput citys error");
        } catch (IOException e1) {

        } finally {
            try {
                if (out != null)
                    out.close();
            } catch (Exception e) {
            }
        }

        File newInternalFile = getDir("newFile", MODE_PRIVATE);

        mStringBuilder.append("getFilesDir() :" + getFilesDir().getAbsolutePath());
        mStringBuilder.append("\n");

        mStringBuilder.append("getDir(\"newFile\") :" + newInternalFile.getAbsolutePath());
        mStringBuilder.append("\n");

        mStringBuilder.append("getCacheDir() :" + getCacheDir().getAbsolutePath());
        mStringBuilder.append("\n");

        //Using the External Storage
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            mStringBuilder.append("getExternalStoragePublicDirectory(picture) :" + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES));
            mStringBuilder.append("\n");

            File[] arrFile = ContextCompat.getExternalFilesDirs(this,null);
            for (File f : arrFile){
                mStringBuilder.append("getExternalFilesDirs() :"+f.getAbsolutePath());
                mStringBuilder.append("\n");
            }

            arrFile = ContextCompat.getExternalCacheDirs(this);
            for (File f : arrFile){
                mStringBuilder.append("getExternalCacheDirs() :"+f.getAbsolutePath());
                mStringBuilder.append("\n");
            }
        }


        mTextView.setText(mStringBuilder.toString());
    }
}


4、Using SQLite Databases

 

posted @ 2016-06-27 08:09  chenyizh  阅读(289)  评论(0)    收藏  举报