android开发实现文件读写
本文实例为大家分享了android实现文件读写的具体代码,供大家参考,具体内容如下
读取
/**
*文件读取
*@paramis文件的输入流
*@return返回文件数组
*/
privatebyte[]read(InputStreamis){
//缓冲区inputStream
BufferedInputStreambis=null;
//用于存储数据
ByteArrayOutputStreambaos=null;
try{
//每次读1024
byte[]b=newbyte[1024];
//初始化
bis=newBufferedInputStream(is);
baos=newByteArrayOutputStream();
intlength;
while((length=bis.read(b))!=-1){
//bis.read()会将读到的数据添加到b数组
//将数组写入到baos中
baos.write(b,0,length);
}
returnbaos.toByteArray();
}catch(IOExceptione){
e.printStackTrace();
}finally{//关闭流
try{
if(bis!=null){
bis.close();
}
if(is!=null){
is.close();
}
if(baos!=null)baos.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
returnnull;
}
写入
/**
*将数据写入文件中
*@parambuffer写入数据
*@paramfos文件输出流
*/
privatevoidwrite(byte[]buffer,FileOutputStreamfos){
//缓冲区OutputStream
BufferedOutputStreambos=null;
try{
//初始化
bos=newBufferedOutputStream(fos);
//写入
bos.write(buffer);
//刷新缓冲区
bos.flush();
}catch(IOExceptione){
e.printStackTrace();
}finally{//关闭流
try{
if(bos!=null){
bos.close();
}
if(fos!=null){
fos.close();
}
}catch(IOExceptione){
e.printStackTrace();
}
}
}
使用
//获取文件输入流
InputStreammRaw=getResources().openRawResource(R.raw.core);
//读取文件
byte[]bytes=read(mRaw);
//创建文件(getFilesDir()路径在data/data/<包名>/files,需要root才能看到路径)
Filefile=newFile(getFilesDir(),"hui.mp3");
booleannewFile=file.createNewFile();
//写入
if(bytes!=null){
FileOutputStreamfos=openFileOutput("hui.mp3",Context.MODE_PRIVATE);
write(bytes,fos);
}
该步骤为耗时操作,最好在io线程执行
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。