1.首先写文件输入输出,那么我们对流要有简单的认识,这里我对流简单向大家解析下
2.写文件存储,我们有两种方式获取到文件流对象
new FileOutput(file,mode);
context.openFileOutput(file, mode);
这两种不推荐使用第一种,因为第一种创建了对象
参数1 是文件名
参数2 是文件存储模式
3.保存文件内容,我们要使用文件输出流
/** * *@param file 文件名 *@param context *@param mode 模式 *@param str 存储物 *@throws Exception */
public static void writeFile(String file,Context context,int mode,String str)throws Exception{
//获取文件的输出流,用来保存文件
FileOutputStream out = context.openFileOutput(file, mode);
//把我们str写入到文件里
out.write(str.getBytes());
//记得流一定要关闭
out.close();
}
4.获取文件内容,我们要使用输入流
/** * *@param file 文件名 *@param context *@return *@throws Exception */
public static String readFile(String file,Context context)throws Exception{
String str=null;
FileInputStream input = context.openFileInput(file);
//字节数组输出流,可以捕获内存缓冲区的数据,转换成字节数组。
ByteArrayOutputStream stream = new ByteArrayOutputStream();
byte[] bytes = new byte[1024];
int length;
//从文件出入流中读取,已数组类型存入byte中
while((length=input.read(bytes))!=-1){
//把数据写入流里
stream.write(bytes,0,length);
}
input.close();
stream.close();
str=stream.toString();
return str;
}
5.创建文件存储4中Mode
Context.MODE_PRIVATE:为默认操作模式,代表该文件是私有数据,只能被应用本身访问,在该模式下,写入的内容会覆盖原文件的内容,如果想把新写入的内容追加到原文件中。可以使用Context.MODE_APPEND
Context.MODE_APPEND:模式会检查文件是否存在,存在就往文件追加内容,否则就创建新文件。
MODE_WORLD_READABLE:表示当前文件可以被其他应用读取;
MODE_WORLD_WRITEABLE:表示当前文件可以被其他应用写入
6.文件储存的存放地址
/data/data//files/
至于流,下次有机会和大家讲解