天天看點

android 讀取raw檔案

在android平台下,除了對應用程式的私有檔案夾中的檔案進行操作外,還可以從資源檔案和 assets

中獲得輸入流讀取資料,這些檔案分别放在應用程式的res/raw 目錄和 assets 目錄下,這些檔案在編譯的時候和其他檔案一起被打包。

    需要注意的是,來自resources和assets

中的檔案隻可以讀取而不能進行寫的操作,下面就通過一個例子來說明如何從 resources 和 assets中的檔案中讀取資訊。首先分别在res/raw 和

assets 目錄下建立兩個文本檔案 "test1.txt"   和 "test2.txt" 用以讀取,結構如下圖。

android 讀取raw檔案

為了避免字元串轉碼帶來的麻煩,可以将兩個文本檔案的編碼格式設定為utf-8。設定編碼格式的方法有很多種,比較簡單的一種是用 windows

的記事本打開文本檔案,在另存為對話框中編碼格式選擇"utf-8" ,如下圖。

android 讀取raw檔案

看一下運作後的效果。

android 讀取raw檔案

package xiaohang.zhimeng;

import java.io.inputstream;

import

org.apache.http.util.encodingutils;

import android.app.activity;

android.graphics.color;

import android.os.bundle;

android.widget.textview;

public class activity02 extends

activity{

    public static final

string encoding = "utf-8";

    textview tv1;

 textview tv2;

 @override

    protected void oncreate(bundle

savedinstancestate) {

 super.oncreate(savedinstancestate);

 setcontentview(r.layout.main);

 tv1 = (textview)findviewbyid(r.id.tv1);

 tv1.settextcolor(color.red);

 tv1.settextsize(15.0f);

        tv2 =

(textview)findviewbyid(r.id.tv2);

 tv2.settextcolor(color.red);

 tv2.settextsize(15.0f);

 tv1.settext(getfromraw());

 tv2.settext(getfromassets("test2.txt"));

 }

    //從resources中的raw

檔案夾中擷取檔案并讀取資料

    public string getfromraw(){

     string result = "";

     try {

         inputstream in =

getresources().openrawresource(r.raw.test1);

         //擷取檔案的位元組數

             int lenght =

in.available();

     //建立byte數組

         byte[]  buffer = new

byte[lenght];

     //将檔案中的資料讀到byte數組中

         in.read(buffer);

             result =

encodingutils.getstring(buffer, encoding);

     } catch (exception e) {

 e.printstacktrace();

            return

result;

    }

 //從assets 檔案夾中擷取檔案并讀取資料

    public string

getfromassets(string filename){

        string

result = "";

            try

{

 inputstream in =

getresources().getassets().open(filename);

}