安卓 SharedPreferences存储+SD卡存储
SharedPreferences
SharedPreferences简称Sp(后面都会称Sp),是一种轻量级的数据存储方式,采用Key/value的方式 进行映射
在手机的/data/data/package_name/shared_prefs/目录下以xml的格式存在
写数据
java代码
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//写数据
SharedPreferences sp = getSharedPreferences("login", MODE_PRIVATE);
SharedPreferences.Editor edit = sp.edit();
edit.putString("name","黑子");
edit.putInt("age",18);
edit.putFloat("num",3.5f);
edit.putBoolean("isman",false);
edit.putLong("id",1424242422);
edit.commit();
}
点击右下角的devices找data/data下项目名你自己起名字.xml
读数据
java代码
//读数据
private void read() {
//得到SharedPreferences对象
//参数一 xml文件的名字 参数二 模式 MODE_PRIVATE 指定该SharedPreferences数据只能被本应用程序读写
SharedPreferences preferences = getSharedPreferences("sgf", MODE_PRIVATE);
//直接读取
//参数一 键 参数二 找不到的时候给默认值
String name=preferences.getString("name","");
int age=preferences.getInt("age",0);
boolean isman=preferences.getBoolean("isman",false);
float num=preferences.getFloat("num",0.0f);
long id=preferences.getLong("id",0l);
Toast.makeText(this, name+":"+age+":"+isman+":"+num+":"+id, Toast.LENGTH_SHORT).show();
}
内部文件存储
openFileOutput
与java 操作文件没有区别.只是路径是唯一的
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = openFileOutput("aa.json", MODE_PRIVATE);
fileOutputStream.write("hello".getBytes());
fileOutputStream.flush();
fileOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
openFileInput
与java 操作文件没有区别.只是路径是唯一的
FileInputStream fileInputStream = null;
try {
fileInputStream= openFileInput("aa.json");
byte[] b = new byte[1024];
int len = 0;
while((len = fileInputStream.read(b)) != -1){
Log.i(TAG, "onClick: "+new String(b,0,len));
}
} catch (Exception e) {
e.printStackTrace();
}