android 讀取raw文件

在Android平臺下,除了對應用程序的私有文件夾中的文件進行操做外,還能夠從資源文件和 Assets 中得到輸入流讀取數據,這些文件分別放在應用程序的res/raw 目錄和 assets 目錄下,這些文件在編譯的時候和其餘文件一塊兒被打包。

    須要注意的是,來自Resources和Assets 中的文件只能夠讀取而不能進行寫的操做,下面就經過一個例子來講明如何從 Resources 和 Assets中的文件中讀取信息。首先分別在res/raw 和 assets 目錄下新建兩個文本文件 "test1.txt"   和 "test2.txt" 用以讀取,結構以下圖。



   爲了不字符串轉碼帶來的麻煩,能夠將兩個文本文件的編碼格式設置爲UTF-8。設置編碼格式的方法有不少種,比較簡單的一種是用 Windows 的記事本打開文本文件,在另存爲對話框中編碼格式選擇"UTF-8" ,以下圖。



看一下運行後的效果。

java

 

package xiaohang.zhimeng;

import java.io.InputStream;
import org.apache.http.util.EncodingUtils;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import 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);
                //獲取文件的字節數
                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;
    }
}

android

相關文章
相關標籤/搜索