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

所属分类: 软件编程 / Android 阅读数: 735
收藏 0 赞 0 分享

一、保存文件到手机内存

/**
   * 保存数据到手机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);

加入写外部存储的权限:

<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)
写入的步骤:

SharedPreferences调用edit()得到一个Editor对象
使用 putBoolean() and putString()添加值
提交事务完成存储
读取时:只需要调用SharedPreferences的getBoolean() and getString()

下面是示例代码:

public class MySharedPreference {
  private Context context;
  private SharedPreferences sp ;
  private Editor edit;
  public MySharedPreference(Context context){
    this.context = context;
  }
  public boolean saveMessage(String name,String pwd){
    boolean flag = false;
     sp = context.getSharedPreferences("userInfo",Context.MODE_PRIVATE);
     //MODE定义了访问的权限现在是本应用可以访问
    edit = sp.edit();
    edit.putString("name", name);
    edit.putString("pwd", pwd);
    flag = edit.commit();//提交事务将数据持久化到存储器中
    return flag;

  }
  public Map<String,Object> getMessage(){
    Map<String,Object> map = new HashMap<String, Object>();
    sp = context.getSharedPreferences("userInfo", Context.MODE_PRIVATE);
    String name = sp.getString("name", "");
    String pwd = sp.getString("pwd", "");
    map.put("name", name);
    map.put("pwd",pwd);
    return map;

  }

}

更多精彩内容其他人还在看

Android样式和主题之选择器的实例讲解

今天小编就为大家分享一篇关于Android样式和主题之选择器的实例讲解,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
收藏 0 赞 0 分享

Android应用动态修改主题的方法示例

今天小编就为大家分享一篇关于Android应用动态修改主题的方法示例,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
收藏 0 赞 0 分享

Flutter 网络请求框架封装详解

这篇文章主要介绍了Flutter 网络请求框架封装详解,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

Flutter倒计时/计时器的实现代码

这篇文章主要介绍了Flutter倒计时/计时器的实现代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
收藏 0 赞 0 分享

Android使用google breakpad捕获分析native cash

这篇文章主要介绍了Android使用google breakpad捕获分析native cash 的相关知识,非常不错,具有一定的参考借鉴价值,需要的朋友可以参考下
收藏 0 赞 0 分享

详解Flutter WebView与JS互相调用简易指南

这篇文章主要介绍了详解Flutter WebView与JS互相调用简易指南,分为JS调用Flutter和Flutter调用JS,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

Android开发实现ListView和adapter配合显示图片和文字列表功能示例

这篇文章主要介绍了Android开发实现ListView和adapter配合显示图片和文字列表功能,涉及Android使用ListView结合adapter适配器实现图文显示功能相关的布局、解析、权限控制等操作技巧,需要的朋友可以参考下
收藏 0 赞 0 分享

Android文字基线Baseline算法的使用讲解

今天小编就为大家分享一篇关于Android文字基线Baseline算法的使用讲解,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
收藏 0 赞 0 分享

Flutter自定义实现神奇动效的卡片切换视图的示例代码

这篇文章主要介绍了Flutter自定义实现神奇动效的卡片切换视图的示例代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

Android实现自定义滑动刻度尺方法示例

这篇文章主要给大家介绍了关于Android实现自定义滑动刻度尺的相关资料,文中通过示例代码介绍的非常详细,对各位Android开发者们具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧
收藏 0 赞 0 分享
查看更多