一、使用到的几个类
File:文件操作类
FileInputStream:文件输入流
FileOutPutStream:文件输出流
ByteArrayOutputStream:缓存输出流
二、文件对象的创建方法
1、获取当前应用文件的文件输入流对象、文件输出流对象
分别是:context.openFileInput(filename)、以及context.openFileOutPut(file,Context.Mode_Private);
context为当前上下文对象。
2、通过指定对象创建
new FileInputStream(文件对象)、new FileOutputStream(文件对象);
三、实例
文件写入:
File file=new File(filename);
FileOutputStream outputStream=context.openFileOutput(filename, Context.MODE_PRIVATE); //创建文件输出流并且指定文件操作模式
outputStream.write(fileContent.getBytes());//写入输出流
outputStream.close();//关闭输出流
文件读取:
/**
* 读取数据
* @param filename 文件名称
* @return
*/
public String read(String filename) throws Exception{
File file=new File(filename);
FileInputStream inputStream= new FileInputStream(file); //创建输入流
ByteArrayOutputStream outStream=new ByteArrayOutputStream(); //缓存输出流
byte[] buffer =new byte[1024]; //创建字节数组
int len=0;
while((len=inputStream.read(buffer))!=-1){ //循环读取数据并且将数据写入到缓存输出流中
outStream.write(buffer, 0, len);
}
return new String(outStream.toByteArray());
}