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

所属分类: 软件编程 / Android 阅读数: 704
收藏 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;

  }

}

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

Retrofit2日志拦截器的使用

这篇文章主要介绍了Retrofit2日志拦截器的使用,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

Android创建外部lib库及自定义View的图文教程

这篇文章主要给大家介绍了关于Android创建外部lib库及自定义View的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
收藏 0 赞 0 分享

Android分享微信小程序失败的一些事小结

这篇文章主要给大家介绍了关于Android分享微信小程序失败一些事,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
收藏 0 赞 0 分享

Android分享微信小程序技巧之图片优化

这篇文章主要给大家介绍了关于Android分享微信小程序技巧之图片优化的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
收藏 0 赞 0 分享

Android Viewpager实现无限循环轮播图

这篇文章主要为大家详细介绍了Android Viewpager实现无限循环轮播图,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

Android中的Bitmap序列化失败的解决方法

这篇文章主要介绍了Android中的Bitmap序列化失败的解决方法,本文通过实例代码给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下
收藏 0 赞 0 分享

Android自定义通用标题栏CustomTitleBar

这篇文章主要为大家详细介绍了Android自定义通用标题栏CustomTitleBar,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

Android组合控件自定义标题栏

这篇文章主要为大家详细介绍了Android组合控件自定义标题栏,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

Android自定义复合控件实现通用标题栏

这篇文章主要为大家详细介绍了Android自定义复合控件实现通用标题栏,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

ExpandableListView实现简单二级列表

这篇文章主要为大家详细介绍了ExpandableListView实现简单二级列表,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享
查看更多