SharedPreferences模式
![image.png](https://upload-images.jianshu.io/upload_images/12474760-8ab80938a1bdc110.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
// 存储的操作
String strName = editTextName.getText().toString();
String strPwd = editTextPwd.getText().toString();
// SharedPreferences 读取
Log.e("strName",strName);
Log.e("passWord",strPwd);
if(strName.equals("admin") && strPwd.equals("123")) {
// 2.1 存储信息到SharedPreferences 参数1:参数名称,参数2: 参数模式
SharedPreferences SharedPreferences = getSharedPreferences("myName",MODE_PRIVATE);
// 2.2 获取editor对象
android.content.SharedPreferences.Editor editor = SharedPreferences.edit();
// 2.3.存储信息
editor.putString("userName",strName);
editor.putString("passWord",strPwd);
// 2.4 指定提交操作
editor.commit();
找到存储的数据在哪里
// 获取数据操作
// 获取参数
SharedPreferences shared = getSharedPreferences("myName",MODE_PRIVATE);
//获取参数的默认值
String user = shared.getString("userName","");
String pwd = shared.getString("passWord","");
editTextName.setText(user);
editTextPwd.setText(pwd);
外部存储
// 点击按钮去写入文件和读取文件操作
public void FnOperate(View view) {
if(!isGrantExternalRW(this)){ // 动态授权
return;
}
// Environment.getExternalStorageDirectory().getAbsolutePath() 绝对路径
String path = Environment.getExternalStorageDirectory().getAbsolutePath()+"/pjtest.txt";
// Environment.getExternalStorageState().equals("mounted") // 是否有内存卡
Log.e("TAG",path+Environment.getExternalStorageState().equals("mounted"));
switch (view.getId()){
case R.id.save:
File f = new File(path);
try {
if (!f.exists()) {
f.createNewFile();
}
FileOutputStream fos = new FileOutputStream(path,true);
String str = infoEdt.getText().toString();
fos.write(str.getBytes());
}catch (IOException ioe){
ioe.printStackTrace();
}
case R.id.read:
// tex
try {
FileInputStream fis = new FileInputStream(path);
byte[] b = new byte[1024];
int len = fis.read(b);
String str2 = new String(b,0,len);
Log.e("str2",str2);
tex.setText(str2);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
动态授权操作
// 动态申请权限
public static boolean isGrantExternalRW(Activity activity) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && activity.checkSelfPermission(
Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
activity.requestPermissions(new String[]{
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
}, 1);
return false;
}
return true;
}
新版本存储地址
内部存储