文章目录
今天来介绍一下Android的数据持久化技术,提供了三种存储方式,还可以存储到SD卡中。
主要介绍这三种:
文件存储
适用于存储较大或复杂的数据文件,比如图像、视频、文档等。
也适合存储简单的文本文件。
SharedPreferences存储
适用于存储简单的键值对数据,比如用户设置和应用配置。
数据量通常较小,数据结构简单。
数据库存储
适用于存储结构化数据,支持复杂的查询和数据管理。
文件存储
使用Context
提供的openFileOutput
和openFileInput
方法,他们返回
存储到文件
openFileOutput()
public class MainActivity extends AppCompatActivity {
private EditText edit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edit = findViewById(R.id.editText);
}
@Override
protected void onDestroy() {
super.onDestroy();
String inputText = edit.getText().toString(); // 获取EditText中的文本
save(inputText);
}
// 将输入的文本保存到文件的方法
private void save(String inputText) {
FileOutputStream out = null; // 声明FileOutputStream变量
BufferedWriter writer = null; // 声明BufferedWriter变量
try {
// 打开名为 "data" 的文件
out = openFileOutput("data", Context.MODE_PRIVATE);
writer = new BufferedWriter(new OutputStreamWriter(out)); // 创建BufferedWriter对象
writer.write(inputText); // 将输入的文本写入文件
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
try {
if (writer != null) {
writer.close();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
读取文件
openFileInput
public class MainActivity extends AppCompatActivity {
private EditText edit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edit = findViewById(R.id.editText);
String inputText = load();
// 如果加载到的文本内容不为空
if (!TextUtils.isEmpty(inputText)) {
// 如果加载到的文本内容不为空
edit.setText(inputText);
// 将光标移动到文本末尾
edit.setSelection(inputText.length());
Toast.makeText(this, "加载成功", Toast.LENGTH_SHORT).show();
}
}
// 加载之前保存的文本内容
private String load() {
FileInputStream input = null;
BufferedReader reader = null;
// 创建 StringBuilder 对象,用于存储加载的文本内容
StringBuilder content = new StringBuilder();
try {
// 打开名为 "data" 的文件
input = openFileInput("data");
// 创建 BufferedReader 对象
reader = new BufferedReader(new InputStreamReader(input));
String line;
while ((line = reader.readLine()) != null) {
content.append(line);
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return content.toString();
}
@Override
protected void onDestroy() {
super.onDestroy();
String inputText = edit.getText().toString();
save(inputText