android中读取原始(Raw)资源

存储在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);
                }
            }
        }
    }

转自:http://hubingforever.blog.163.com/blog/static/17104057920105164250608/

posted @ 2012-09-05 16:19  子福当自强  阅读(845)  评论(0编辑  收藏  举报
悟道