存储在
res/raw
位置的文件不会被平台编译,而是作为可用的原始资源。
读取原始资源非常简单。
首先调用 Context.getResource 获得当前应用程序上下文的 Resources引用 .
然后调用 openRawResource(intid) 得到 InputStream .
最后,操作 InputStream 得到数据。
注意:把文件放在res/raw目录下,则R类会自动提供该id.
提速文件读取
其原理就是读的时候,先把文件的一些数据读到缓冲中。这样的好处是如果读的内容已经在缓冲中,就读缓冲的数据。
如果没有,就让缓冲先从文件读取数据,然后再从缓冲读数据。这样的好处是减少对文件的操作次数,从而达到提高性能的目的。
坏处是要额外的内存来做缓冲区.
示例代码如下:
InputStreamis=resources.openRawResource(R.raw.hubin);
BufferedInputStreambuf=newBufferedInputStream(is);
示例1:
void readRawFile()
{
Stringcontent;
Resourcesresources=this.getResources();
InputStreamis=null;
try{
is=resources.openRawResource(R.raw.hubin);
bytebuffer[]=newbyte[is.available()];
is.read(buffer);
content=newString(buffer);
Log.i(tag,"read:"+content);
}
catch(IOExceptione)
{
Log.e(tag,"writefile",e);
}
finally
{
if(is!=null)
{
try{
is.close();
} catch(IOExceptione)
{
Log.e(tag,"closefile",e);
}
}
}
}
读取原始资源非常简单。
首先调用 Context.getResource 获得当前应用程序上下文的 Resources引用 .
然后调用 openRawResource(intid) 得到 InputStream .
最后,操作 InputStream 得到数据。
注意:把文件放在res/raw目录下,则R类会自动提供该id.
提速文件读取
其原理就是读的时候,先把文件的一些数据读到缓冲中。这样的好处是如果读的内容已经在缓冲中,就读缓冲的数据。
如果没有,就让缓冲先从文件读取数据,然后再从缓冲读数据。这样的好处是减少对文件的操作次数,从而达到提高性能的目的。
坏处是要额外的内存来做缓冲区.
示例代码如下:
InputStreamis=resources.openRawResource(R.raw.hubin);
BufferedInputStreambuf=newBufferedInputStream(is);
示例1:
void readRawFile()
{
Stringcontent;
Resourcesresources=this.getResources();
InputStreamis=null;
try{
is=resources.openRawResource(R.raw.hubin);
bytebuffer[]=newbyte[is.available()];
is.read(buffer);
content=newString(buffer);
Log.i(tag,"read:"+content);
}
catch(IOExceptione)
{
Log.e(tag,"writefile",e);
}
finally
{
if(is!=null)
{
try{
is.close();
} catch(IOExceptione)
{
Log.e(tag,"closefile",e);
}
}
}
}