android中读取原始(Raw)资源
2015-08-25 15:24
316 查看
存储在res/raw位置的文件不会被平台编译,而是作为可用的原始资源。
读取原始资源非常简单。
首先调用Context.getResource获得当前应用程序上下文的Resources引用.
然后调用openRawResource(int id)得到InputStream.
最后,操作InputStream得到数据。
注意:把文件放在res/raw目录下,则R类会自动提供该id.
提速文件读取
其原理就是读的时候,先把文件的一些数据读到缓冲中。这样的好处是如果读的内容已经在缓冲中,就读缓冲的数据。
如果没有,就让缓冲先从文件读取数据,然后再从缓冲读数据。这样的好处是减少对文件的操作次数,从而达到提高性能的目的。
坏处是要额外的内存来做缓冲区.
示例代码如下:
InputStream is=resources.openRawResource(R.raw.hubin);
BufferedInputStream buf = new BufferedInputStream(is);
示例1:
void readRawFile()
{
String content;
Resources resources=this.getResources();
InputStream is=null;
try{
is=resources.openRawResource(R.raw.hubin);
byte buffer[]=new byte[is.available()];
is.read(buffer);
content=new String(buffer);
Log.i(tag, "read:"+content);
}
catch(IOException e)
{
Log.e(tag, "write file",e);
}
finally
{
if(is!=null)
{
try{
is.close();
}catch(IOException e)
{
Log.e(tag, "close file",e);
}
}
}
}
读取原始资源非常简单。
首先调用Context.getResource获得当前应用程序上下文的Resources引用.
然后调用openRawResource(int id)得到InputStream.
最后,操作InputStream得到数据。
注意:把文件放在res/raw目录下,则R类会自动提供该id.
提速文件读取
其原理就是读的时候,先把文件的一些数据读到缓冲中。这样的好处是如果读的内容已经在缓冲中,就读缓冲的数据。
如果没有,就让缓冲先从文件读取数据,然后再从缓冲读数据。这样的好处是减少对文件的操作次数,从而达到提高性能的目的。
坏处是要额外的内存来做缓冲区.
示例代码如下:
InputStream is=resources.openRawResource(R.raw.hubin);
BufferedInputStream buf = new BufferedInputStream(is);
示例1:
void readRawFile()
{
String content;
Resources resources=this.getResources();
InputStream is=null;
try{
is=resources.openRawResource(R.raw.hubin);
byte buffer[]=new byte[is.available()];
is.read(buffer);
content=new String(buffer);
Log.i(tag, "read:"+content);
}
catch(IOException e)
{
Log.e(tag, "write file",e);
}
finally
{
if(is!=null)
{
try{
is.close();
}catch(IOException e)
{
Log.e(tag, "close file",e);
}
}
}
}
相关文章推荐
- android 学习笔记 内容提供器ContentResolver
- Android 给控件自定义Shape背景
- ffmpeg移植到Android
- android TextView 带滚动条,和ScrollView 用法(暂时觉得ScrollView滑动速度比较快)
- Android 多分辨率机适应
- WeakReference 在android中的应用
- Android基础入门教程——2.3.11 Date & Time组件(上)
- AndroidMainifest标签说明2——<activity>
- android 图片尺寸 资料
- 49、android ListView几个比较特别的属性
- Android NDK资料
- A2DP Sink, AVRCP Controller and HFP Client in Android L
- Android开发之HelloWorld程序
- Android FragmentManager BackStackRecord.run throwing NullPointerException
- Android studio无法创建新项目问题解决方案一
- Android 4.4 源码编译
- Android在不同状态下的调试方法
- 【ActionBar】Android ActionBar完全解析,使用官方推荐的最佳导航栏(下)
- android 进程间通信---bind的前世
- 【ActionBar】Android ActionBar完全解析,使用官方推荐的最佳导航栏(上)