【Android】本地数据存储之文件存储和SharedPreferences

数据存储方式

Android平台提供了五种数据存储的方式:

  • SharedPreferences:可以用来存储简单的配置信息,是用的XML格式将数据存储到设备中。
  • SQLite数据库:这个是Android自带的一个轻量级数据库。

  • ContentProvider:Android四大组件之一,主要应用于应用程序之间的数据交换。

  • 网络存储:将数据存储到云服务器上,通过网络提供的存储空间来存储数据。

文件存储

这里主要讲解内部存储,就是将数据以文件的形式存储到应用中。

内部存储使用的是Context提供的openFileInput()和openFileOutput()方法,示例:

FileOutputStream out = openFileOutput(String name, int mode);
FileInputStream in = openFileInput(String name);

上述代码中,openFileOutput方法是用于将数据存储到相应的文件,openFileInput方法是将数据从文件读取到应用程序中(这里如果分不清的话可以这么记住: 我们的视角始终是站在应用程序这边,将数据从我们这写到对面文件中就是out,将数据从对面文件拿回到我们这就是in)。mode表示文件的操作模式,常用的就两种:MODE_PEIVATE,MODE_APPEND。前一种是表示该文件只能被当前程序读写,而且数据是会被覆盖的;后一种表示该文件可以追加。

存储数据示例:

private String fileName = "data.text"; //文件的名称
private String content = "helloWorld!"; //要保存的内容
FileOutputStream out = null;

try {
  out = openFileOutput(fileName, MODE_PRIVATE);
  out.write(content.getBytes()); //将数据写入对应文件中
} catch (FileNotFoundException e) {
  e.printStackTrace();
} catch (IOException e) {
  e.printStackTrace();
} finally{
  if (out != null) {
    try {
       out.close();   //关闭流
    } catch (IOException e) {
       e.printStackTrace();
    }
  }
}

读取数据示例:

private String fileName = "data.text"; //文件的名称
private String content = ""; //要读出的内容
FileInputStream in = null;

try {
  in = openFileInput(fileName);
  byte[] buffer = new byte[in.available()]; //创建缓冲区,并获取文件长度
  in.read(buffer);  //读取文件内容到缓冲区
  content = new String(buffer); //转换成字符串
} catch (FileNotFoundException e) {
  e.printStackTrace();
} catch (IOException e) {
  e.printStackTrace();
} finally{
  if (in != null) {
    try {
       in.close();   //关闭流
    } catch (IOException e) {
       e.printStackTrace();
    }
  }
}

SharedPreferences

当程序中有一些少量数据需要持久化存储时,可以使用SharedPreferences进行存储,包括用户名,密码,一些配置信息等。

大致的步骤有获取SharedPreferences示例,获取编辑器对象,写入数据,提交数据四个步骤。

读取数据主要有两步:获取实例对象,获取数据

删除数据

Original: https://blog.csdn.net/qq_45933810/article/details/121900764
Author: F桨鹏F
Title: 【Android】本地数据存储之文件存储和SharedPreferences

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/816031/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球