Android本地存储有三个方法:files、sdcard、SharedPreferences
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();