码迷,mamicode.com
首页 > 其他好文 > 详细

存储选择(Storage Options)

时间:2016-07-06 20:07:53      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:

一. SharePreferences: 通过键值对的方式存储私有的原始数据

  1. 获取SharePrefereces对象的两种方法

     (1 getSharedPreferences(String name, int mode)

     (2) getPreferences(int mode)

  2. 写入值的步骤

     (1)调用edit, 得到SharePreferences.Editor对象

     (2)通过如putBoolean(String key, boolean value)的方法添加键值对

     (3)调用commit()保存

 3. 读取值

     通过SharePrefereces的getBoolean(String key, boolean defValue)等方法

eg:

public class Calc extends Activity {
    public static final String PREFS_NAME = "MyPrefsFile";

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

       // Restore preferences
       SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
       boolean silent = settings.getBoolean("silentMode", false);
       setSilent(silent);
    }

    @Override
    protected void onStop(){
       super.onStop();

      // We need an Editor object to make preference changes.
      // All objects are from android.context.Context
      SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
      SharedPreferences.Editor editor = settings.edit();
      editor.putBoolean("silentMode", mSilentMode);

      // Commit the edits!
      editor.commit();
    }
}

 

二. 使用内部存储器

  1. 创建文件并且将其写入到内部存储器

   (1)调用openFileOutput(String name, int mode),打开一个文件(不存在就创建),返回FileOutputStream对象

   (2)调用write(byte[] buffer) 写入到文件

   (3)调用close()将流关闭

String FILENAME = "hello_file";
String string = "hello world!";

FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();

  2. 从内部存储器中读取文件

   (1)调用openFileInput(String name)返回FileInputStream对象 

   (2)调用read(byte[] buffer, int byteOffset, int byteCount)读取流

   (3)调用close()将流关闭

 3.其它一些有用的方法

Log.i(TAG, getCacheDir().getPath())  //data/data/包名/caches
Log.i(TAG, getFilesDir().getPath())    //data/data/包名/files

  

 

  

 

存储选择(Storage Options)

标签:

原文地址:http://www.cnblogs.com/mmyz-sysu-panjn/p/Storage-Options.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!