概述
之前的文章有提到,Android应用程序的配置信息我们会借用Sharedpreferences进行保存,但其只能存储(key,value)形式的字典数据,而且如果数据量过大,会很影响效能,这个时候可能就要考虑其他的保存方式。
保存到外部sd卡需要单独申请权限,如果使用File文本文件的形式保存到应用程序目录里,则可能直接使用FileOutputStream进行写入。
档案存储位置
<data/data/com.zqunyan.androidstudy/files/test.txt> //中间的目录为你应用程序的项目包名
写入档案
try{
//只能指定档案名称及副档名,无法指定路径,档案存储于系统内部指定位置中
//档案模式一般使用MODE_PRIVATE,如果想要追加则可使用MODE_APPEND
FileOutputStream fout = openFileOutput("test.txt", MODE_PRIVATE);
//为了提高写入效能,使用BufferedOutputStream进行写操作
BufferedOutputStream buffout = new BufferedOutputStream(fout);
//写入参数只接收byte类别,这里要将字串进行转换
buffout.write(str.getBytes());
buffout.write("\n".getBytes());
//写入完成后,关闭写入流
buffout.close();
}catch(Exception e){
e.printStackTrace();
}
读取档案
try{
FileInputStream fin = openFileInput("test.txt");
BufferedInputStream buffin = new BufferedInputStream(fin);
//定义每次读取的字节数
byte[] buffbyte = new byte[20];
String strResult = "";
//利用循环,每次读取buffbyte个字节,直到档案结束
do{
//获取实际读取到的字节数
int flag = buffin.read(buffbyte);
if(flag == -1) break;
else{
//将读取到的字节数组转换为字串
String str = new String(buffbyte, 0, flag);
strResult = strResult + str;
}while(true);
}
buffin.close();
}catch(Exception e){
e.printStackTrace();
}
清空资料
//以覆写的方式打开档案再关闭,将清空档案内容
FileOutputStream fout = openFileOutput("test.txt", MODE_PRIVATE);
fout.close();