Android应用开发中数据的保存方式总结

2019-12-10 18:57:27丽君

加入写外部存储的权限:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

public static void save(String name ,String password) throws Exception{
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
File file = new File(Environment.getExternalStorageDirectory(),"info.txt");
//也可直接写/sdcard/info.txt 先判断sd卡是否存在
    FileOutputStream fos = new FileOutputStream(file);
    String txt = name+":"+password;
    fos.write(txt.getBytes());
    fos.flush();
    fos.close();
// 使用RandomAccessFile像文件追加内容FileOutputStream会把原有的文件内容清空
//RandomAccessFile raf = new RandomAccessFile(file,"rw");
//raf.seek(file.length()); 将文件指针移动到最后
//raf.write(name.getBytes()+password.getBytes());
//raf.close();
  }
}

//读取文件 加入读取权限
public static String read(){
      try {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
          File sdcardDir = Environment.getExternalStorageDirectory();
          FileInputStream fis = new FileInputStream(sdcardDir.getCanonicalPath() + "info.txt");
          BufferedReader br = new BufferedReader(new InputStreamReader(fis));
          StringBuilder sb = new StringBuilder("");
          String line = null;
          while ((line = br.readLine())!= null){
            sb.append(line);
          }
          return sb.toString();
        }
      } catch (Exception e) {

        e.printStackTrace();
      }
      return null;
    }

三、Sharedpreferences的使用
SharedPreference是开发中常用的一种存储方式,主要存储一些系统不变的参数如是否是第一次进入应用程序等,通过键值对的方式进行存储
可以存储的类型:booleans, floats, ints, longs,strings.

getSharedPreferences() - 存储多个参数
getPreferences() - 仅存储一个参数并且不需要指定名字(key)
写入的步骤: