本地数据存储的两种方式
1.Sharefrence 私有空间
2.sdk外部存储空间
Sharefarence
1.获取sharefarence实例对象,通过getShareference("文件名",读写方式)
Sharefarence mSharefarence= getShareference("name",Context.MODE.PRIVATE)
是支持单线程读写操作的
2.再获取Editor对象。通过sharefarence.edit();
3.增加键值editor.putString("KEY","VALUE").putInt("Key","value").commit();
4.获取键值:sharefarence.getString("KEY")
应用场景:开关,通知状态等
内部存储器卡
1.接通路径:File cacheDir=getCacheDir()
2.创建文件:File parentDir=new File(cacheDir,"mycache")
3.判断主目录是否存在:
if(!parentDir.exsits()){
parentDir.mkdirs()
}
File file=new File(parentDir,"mytxt")
file.write("内容")
file.flush();
file.close();
获取值
FileReader filereader=new FileRear(文件)
ButterReader bt=new ButterReader(filereader);
String line=null;
while((line=bt.readLine())!=null){
log.e(line);
bt.close();
filereader.close();
//记得关闭流,捕获异常
}
外部存储sdk(注:以下代码不是手写输入)
1.添加权限
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
挂载/卸载
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
2.判断sdk是否可读
if (!TextUtils.equals(Environment.getExternalStorageState(), Environment.MEDIA_MOUNTED)) {
return;
}
File fileDir=Environment.getExternalStorageDirectory();
File parentDir=new File(fileDir,"cache");
if (!parentDir.exists()){
parentDir.mkdir();
}
File file=new File(parentDir,"my.txt");
try {
FileWriter fileWriter=new FileWriter(file);
fileWriter.write("this is a file");
fileWriter.flush();;
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
//read
try {
FileReader fileReader=new FileReader(file);
BufferedReader bufferedReader=new BufferedReader(fileReader);
String line=null;
while ((line=bufferedReader.readLine())!=null){
Log.e("lxn","line"+line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
网友评论