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

时间:2021-11-12 02:45:54

一、保存文件到手机内存

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
   * 保存数据到手机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();
  }
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
   * 获取保存的数据
   * @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空间的大小:

?
1
2
3
4
5
6
7
8
9
10
11
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);

加入写外部存储的权限:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<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();
  }
}
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//读取文件 加入读取权限
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()

下面是示例代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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;
 
  }
 
}