Android应用开发中数据的保存方式总结
一、保存文件到手机内存
/**
*保存数据到手机rom的文件里面.
*@paramcontext应用程序的上下文提供环境
*@paramname用户名
*@parampassword密码
*@throwsException
*/
publicstaticvoidsaveToRom(Contextcontext,Stringname,Stringpassword)throwsException{
//Filefile=newFile("/data/data/com.itheima.login/files/info.txt");
Filefile=newFile(context.getFilesDir(),"info.txt");//该文件在data下的files文件夹下getCacheDir()在cache文件夹下文件大小不要超过1Mb
FileOutputStreamfos=newFileOutputStream(file);
Stringtxt=name+":"+password;
fos.write(txt.getBytes());
fos.flush();
fos.close();
}
/**
*获取保存的数据
*@paramcontext
*@return
*/
publicstaticMap<String,String>getUserInfo(Contextcontext){
Filefile=newFile(context.getFilesDir(),"info.txt");
try{
FileInputStreamfis=newFileInputStream(file);
//也可直接读取文件Stringresult=StreamTools.readFromStream(fis);
BufferedReaderbr=newBufferedReader(newInputStreamReader(fis));
Stringstr=br.readLine();
String[]infos=str.split(":");
Map<String,String>map=newHashMap<String,String>();
map.put("username",infos[0]);
map.put("password",infos[1]);
returnmap;
}catch(Exceptione){
e.printStackTrace();
returnnull;
}
}
//最后可以直接调用上面的方法读取信息
Map<String,String>map=getUserInfo(this);
If(map!=null){
Textview.setText(map.get(“username”));
}
二、保存文件到SD卡
获取手机sd空间的大小:
Filepath=Environment.getExternalStorageDirectory();
StatFsstat=newStatFs(path.getPath());
longblockSize=stat.getBlockSize();
longtotalBlocks=stat.getBlockCount();
longavailableBlocks=stat.getAvailableBlocks();
longtotalSize=blockSize*totalBlocks;
longavailSize=blockSize*availableBlocks;
StringtotalStr=Formatter.formatFileSize(this,totalSize);
StringavailStr=Formatter.formatFileSize(this,availSize);
tv.setText("总空间"+totalStr+"\n"+"可用空间"+availStr);
加入写外部存储的权限:
<uses-permissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
publicstaticvoidsave(Stringname,Stringpassword)throwsException{
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
Filefile=newFile(Environment.getExternalStorageDirectory(),"info.txt");
//也可直接写/sdcard/info.txt先判断sd卡是否存在
FileOutputStreamfos=newFileOutputStream(file);
Stringtxt=name+":"+password;
fos.write(txt.getBytes());
fos.flush();
fos.close();
//使用RandomAccessFile像文件追加内容FileOutputStream会把原有的文件内容清空
//RandomAccessFileraf=newRandomAccessFile(file,"rw");
//raf.seek(file.length());将文件指针移动到最后
//raf.write(name.getBytes()+password.getBytes());
//raf.close();
}
}
//读取文件加入读取权限
publicstaticStringread(){
try{
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
FilesdcardDir=Environment.getExternalStorageDirectory();
FileInputStreamfis=newFileInputStream(sdcardDir.getCanonicalPath()+"info.txt");
BufferedReaderbr=newBufferedReader(newInputStreamReader(fis));
StringBuildersb=newStringBuilder("");
Stringline=null;
while((line=br.readLine())!=null){
sb.append(line);
}
returnsb.toString();
}
}catch(Exceptione){
e.printStackTrace();
}
returnnull;
}
三、Sharedpreferences的使用
SharedPreference是开发中常用的一种存储方式,主要存储一些系统不变的参数如是否是第一次进入应用程序等,通过键值对的方式进行存储
可以存储的类型:booleans,floats,ints,longs,strings.
getSharedPreferences()-存储多个参数
getPreferences()-仅存储一个参数并且不需要指定名字(key)
写入的步骤:
SharedPreferences调用edit()得到一个Editor对象
使用putBoolean()andputString()添加值
提交事务完成存储
读取时:只需要调用SharedPreferences的getBoolean()andgetString()
下面是示例代码:
publicclassMySharedPreference{
privateContextcontext;
privateSharedPreferencessp;
privateEditoredit;
publicMySharedPreference(Contextcontext){
this.context=context;
}
publicbooleansaveMessage(Stringname,Stringpwd){
booleanflag=false;
sp=context.getSharedPreferences("userInfo",Context.MODE_PRIVATE);
//MODE定义了访问的权限现在是本应用可以访问
edit=sp.edit();
edit.putString("name",name);
edit.putString("pwd",pwd);
flag=edit.commit();//提交事务将数据持久化到存储器中
returnflag;
}
publicMap<String,Object>getMessage(){
Map<String,Object>map=newHashMap<String,Object>();
sp=context.getSharedPreferences("userInfo",Context.MODE_PRIVATE);
Stringname=sp.getString("name","");
Stringpwd=sp.getString("pwd","");
map.put("name",name);
map.put("pwd",pwd);
returnmap;
}
}