欢迎来到代码驿站!

当前位置:首页 >

android开发实现文件读写

时间:2020-07-28 10:01:01|栏目:|点击:

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

读取

/**
* 文件读取
* @param is 文件的输入流
* @return 返回文件数组
*/
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;
}

写入

/**
 * 将数据写入文件中
 * @param buffer 写入数据
 * @param fos  文件输出流
 */
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线程执行

上一篇:vue中touch和click共存的解决方式

栏    目:

下一篇:R语言ggplot2边框背景去除的实现

本文标题:android开发实现文件读写

本文地址:http://www.codeinn.net/misctech/2700.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有