1. 程式人生 > >android中讀取原始(Raw)資源

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);
                }
            }
        }        
    }