第五周随笔--SharePreferences与文件管理

2016-06-12  本文已影响0人  關kwan

SharePreferences

用于存储简单的数值;

主要操作流程

写入或修改数据 读取数据

**SharedPreferences()的四种操作模式: **


管理文件

存储方式:
如何存储在外部
//创建File
//File(“指定目录路径”, “文件名”)
//getFilesDir():Activity的一个方法,即当前Activity的路径
File file = new File(getFilesDir(), "test01");
file.createNewFile();

Log.i("aaa", "getFilesDir() 路径:" + getFilesDir().getAbsolutePath());
Log.i("aaa", "file 路径:" + file.getAbsolutePath());

try {    
    Boolean isSuccess = file.createNewFile();
} catch (IOException e) {    
    Log.i("create File error:", e.toString());   
    e.printStackTrace();
}
Log
//写数据
try {    
    FileOutputStream fileOutputStream = openFileOutput("test02", MODE_PRIVATE);    
    String str = "hello lin";    
    try {        
        fileOutputStream.write(str.getBytes());      
        fileOutputStream.close();   
    } catch (IOException e) {        
        e.printStackTrace();    }
} catch (FileNotFoundException e) {   
    e.printStackTrace();
}
区别

SharePreferences只能存储一些小的数据;
而外部存储可以存储比较大的数据,扩展性更好、更灵活;


读取文件

注意:官方推荐Environment.getExternalStorageDirectory().getPath()来获取sdcard的路径,不要直接写“/sdcar/text/a.txt”。

上一篇 下一篇

猜你喜欢

热点阅读