2024-6-10 20:55:08
以下内容源自《【Android】》
仅供学习交流使用
禁止其他平台发布时删除以下此话
本文首次发布于CSDN平台
作者是CSDN@日星月云
博客主页是https://jsss-1.blog.csdn.net
禁止其他平台发布时删除以上此话
【天哥】Android开发视频教程最新版 Android Studio开发
图片资源来自:
https://github.com/jinjungle/skypan-yes-code
日星月云 / 安卓基础学习:https://gitee.com/jsss-1/android-basic-learning
jsss-1 / android-basic-learning:https://github.com/jsss-1/android-basic-learning
2024-6-10 20:55:08
//MODE_PRIVATE:只在本应用内读写
//MODE_WORLD_READABLE:其他应用可以读,存在安全性问题,废弃了
//MODE_WORLD_WRITEABLE:其他应用可以写,存在安全性问题,废弃了
//MODE_APPEND:追加文件而不是覆盖文件
mSharedPreferences = getSharedPreferences("data", MODE_PRIVATE);
mEditor = mSharedPreferences.edit();
读操作
mEditor.putString("name", mEtName.getText().toString());
//同步存储
mEditor.commit();
//异步存储:先从到内存中,异步刷盘到手机
mEditor.apply();
写操作
mTvContent.setText(mSharedPreferences.getString("name",""));
文件目录
/data/data//shared_prefs 


DataStorageActivity
SharedPreferencesActivity
activity_data_storage.xml
activity_shared_preferences.xml



2024-6-10 21:55:54
2024-6-11 16:57:13
//存储数据
private void save(String content) {
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = openFileOutput(mFileName, MODE_PRIVATE);
fileOutputStream.write(content.getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//读取数据
private String read() {
FileInputStream fileInputStream = null;
try {
fileInputStream = openFileInput(mFileName);
byte[] buff = new byte[1024];
StringBuilder sb = new StringBuilder("");
int len = 0;
while ((len = fileInputStream.read(buff)) > 0) {
sb.append(new String(buff, 0, len));
}
return sb.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
save
// fileOutputStream = openFileOutput(mFileName, MODE_PRIVATE);
//创建文件夹
// File dir = new File(Environment.getExternalStorageDirectory(), "example");
String path = getApplicationContext().getExternalFilesDir(null).getAbsolutePath();
File dir = new File(path, "example");
if (!dir.exists()) {
dir.mkdirs();
}
//创建文件
File file = new File(dir, mFileName);
if (!file.exists()) {
file.createNewFile();
}
read
// fileInputStream = openFileInput(mFileName);
// File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "example", mFileName);
String path = getApplicationContext().getExternalFilesDir(null).getAbsolutePath();
File file = new File(path + File.separator + "example", mFileName);
迎着日光月光星光,直面风霜雨霜雪霜。