我是靠谱客的博主 精明仙人掌,这篇文章主要介绍android开发实现文件读写,现在分享给大家,希望可以做个参考。

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

读取

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/** * 文件读取 * @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; }

写入

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/** * 将数据写入文件中 * @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(); } } }

使用

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//获取文件输入流 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开发实现文件读写内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(116)

评论列表共有 0 条评论

立即
投稿
返回
顶部