美文网首页
Android基础---存储

Android基础---存储

作者: To_Be_Better | 来源:发表于2018-04-04 16:58 被阅读0次

Android本地存储有三个方法:filessdcardSharedPreferences

files存储

可以使用context来获取files的输入输出流进行读写

try {
        FileOutputStream fos = context.openFileOutput("test.txt", Context.MODE_PRIVATE);
        String str = "This is test";
        fos.write(str.getBytes());
    } catch (IOException e) {
        e.printStackTrace()
 }

sdcard存储

使用Environment来获取sdcard的状态信息,先判断是否挂载,再判断大小进行存储

File sdcard_file = Environment.getExternalStorageDirectory();
long usablespace = sdcard_file.getUsableSpace();
long totlespace = sdcard_file.getTotalSpace();
String usabelspace_str = Formatter.formatFileSize(context,usablespace);
String totlespace_str = Formatter.formatFileSize(context,totlespace);
Log.i("savedatabysdcard: ", "usablespace: "+usabelspace_str+"   totlespace: "+totlespace_str);
try {
    String path = Environment.getExternalStorageDirectory().getPath();
    File testFile = new File(path,"test.txt");
    FileOutputStream fos = new FileOutputStream(testFile);
    fos.write("This is Test".getBytes());
} catch (IOException e) {
    e.printStackTrace();
}

SharedPreferences存储

先用context获取sp对象,再获取editor对象,最后apply提交

SharedPreferences sp = context.getSharedPreferences("test.txt", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString("Test","This is Test");
editor.apply();

相关文章

网友评论

      本文标题:Android基础---存储

      本文链接:https://www.haomeiwen.com/subject/hljnzxtx.html