android資源文件(assets and raw) 的讀寫

在開發中,對於一些資源文件(較大時),通常採取IO的讀取方式

我通常根據類型和大小來區分放置位置

下面說下,兩種文件下的讀取方法

一.assets

    /**
     * 使用Assets中的文件
     */
    private void readAssets() {
        et1 = (EditText) findViewById(R.id.et1);
        AssetManager assetManager = getAssets();
        try {
            InputStream inputStream = assetManager.open("test.txt");
            et1.setText(read(inputStream));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

二.raw 

 /**
     * 使用Raw中的文件
     */
    private void readRaw() {
        et2 = (EditText) findViewById(R.id.et2);
        InputStream inputStream = getResources().openRawResource(R.raw.test);
        et2.setText(read(inputStream));
    }
 
    /**
     * 進行IO流讀寫
     *
     * @param inputStream
     * @return oStream.toString() or “文件讀寫失敗”
     */
    private String read(InputStream inputStream) {
 
        try {
            ByteArrayOutputStream oStream = new ByteArrayOutputStream();
            int length;
            while ((length = inputStream.read()) != -1) {
                oStream.write(length);
            }
            return oStream.toString();
        } catch (IOException e) {
            return "文件讀寫失敗";
        }
    }
就這樣

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章