这篇文章主要为大家详细介绍了android开发实现文件读写,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
本文实例为大家分享了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线程执行
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程学习网。
织梦狗教程
本文标题为:android开发实现文件读写
基础教程推荐
猜你喜欢
- Android中的webview监听每次URL变化实例 2023-01-23
- Android开发使用RecyclerView添加点击事件实例详解 2023-06-15
- android studio按钮监听的5种方法实例详解 2023-01-12
- Flutter手势密码的实现示例(附demo) 2023-04-11
- IOS 播放系统提示音使用总结(AudioToolbox) 2023-03-01
- Android多返回栈技术 2023-04-15
- iOS开发教程之XLForm的基本使用方法 2023-05-01
- IOS应用内跳转系统设置相关界面的方法 2022-11-20
- 解决Android Studio突然不显示logcat日志的问题 2023-02-04
- Flutter绘图组件之CustomPaint使用详解 2023-05-12
