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

2019-12-10 18:57:27丽君
易采站长站为您分析Android应用开发中数据的保存方式总结,包括对ROM、SD卡、SharedPreference这三种方式实现的核心代码的精选,需要的朋友可以参考下  

一、保存文件到手机内存

/**
   * 保存数据到手机rom的文件里面.
   * @param context 应用程序的上下文 提供环境
   * @param name 用户名
   * @param password 密码
   * @throws Exception
   */
public static void saveToRom(Context context, String name , String password) throws Exception{
    //File file = new File("/data/data/com.itheima.login/files/info.txt");
    File file = new File(context.getFilesDir(),"info.txt");//该文件在data下的files文件夹下getCacheDir()在cache文件夹下 文件大小不要超过1Mb
    FileOutputStream fos = new FileOutputStream(file);
    String txt = name+":"+password;
    fos.write(txt.getBytes());
    fos.flush();
    fos.close();
  }
/**
   * 获取保存的数据
   * @param context
   * @return
   */
public static Map<String,String> getUserInfo(Context context) {
    File file = new File(context.getFilesDir(),"info.txt");
    try {
      FileInputStream fis = new FileInputStream(file);
      //也可直接读取文件String result = StreamTools.readFromStream(fis);
      BufferedReader br = new BufferedReader(new InputStreamReader(fis));
      String str = br.readLine();
      String[] infos = str.split(":");
      Map<String,String> map = new HashMap<String, String>();
      map.put("username", infos[0]);
      map.put("password", infos[1]);
      return map;
    } catch(Exception e) {

      e.printStackTrace();
      return null;
    }

  }
//最后可以直接调用上面的方法读取信息
Map<String, String> map = getUserInfo(this);
If(map!=null){
Textview.setText(map.get(“username”));
}

二、保存文件到SD卡
获取手机sd空间的大小:

File path = Environment.getExternalStorageDirectory();
    StatFs stat = new StatFs(path.getPath());
    long blockSize = stat.getBlockSize();
    long totalBlocks = stat.getBlockCount();
    long availableBlocks = stat.getAvailableBlocks();
    long totalSize = blockSize*totalBlocks;
    long availSize = blockSize * availableBlocks;

    String totalStr = Formatter.formatFileSize(this,totalSize);
    String availStr = Formatter.formatFileSize(this, availSize);
    tv.setText("总空间"+totalStr+"n"+"可用空间"+availStr);