栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 移动开发 > Android

android开发实现文件读写

Android 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

android开发实现文件读写

本文实例为大家分享了android实现文件读写的具体代码,供大家参考,具体内容如下

读取


private byte[] read(InputStream is) {
  //缓冲区inputStream
  BufferedInputStream bis = null;
  //用于存储数据
  ByteArrayOutputStream baos = null;
  try {
    //每次读1024
    byte[] b = new byte[1024];
    //初始化
    bis = new BufferedInputStream(is);
    baos = new ByteArrayOutputStream();
    
    int length;
    while ((length = bis.read(b)) != -1) {
      //bis.read()会将读到的数据添加到b数组
      //将数组写入到baos中
      baos.write(b, 0, length);
    }
    return baos.toByteArray();

  } catch (IOException e) {
    e.printStackTrace();
  } finally {//关闭流
    try {
      if (bis != null) {
 bis.close();
      }
      if (is != null) {
 is.close();
      }

      if (baos != null) baos.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  return null;
}

写入


private void write(byte[] buffer, FileOutputStream fos) {
  //缓冲区OutputStream
  BufferedOutputStream bos = null;
  try {
    //初始化
    bos = new BufferedOutputStream(fos);
    //写入
    bos.write(buffer);
    //刷新缓冲区
    bos.flush();
  } catch (IOException e) {
    e.printStackTrace();
  } finally {//关闭流
    try {
      if (bos != null) {
 bos.close();
      }
      if (fos != null) {
 fos.close();
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

使用

//获取文件输入流
InputStream mRaw = getResources().openRawResource(R.raw.core);

//读取文件
byte[] bytes = read(mRaw);

//创建文件(getFilesDir()路径在data/data/<包名>/files,需要root才能看到路径)
File file = new File(getFilesDir(), "hui.mp3");
boolean newFile = file.createNewFile();

//写入
if (bytes != null) {
 FileOutputStream fos = openFileOutput("hui.mp3", Context.MODE_PRIVATE);
 write(bytes, fos);
}

该步骤为耗时操作,最好在io线程执行

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/153950.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号