android 读取raw文件

在Android平台下,除了对应用程序的私有文件夹中的文件进行操作外,还可以从资源文件和 Assets 中获得输入流读取数据,这些文件分别放在应用程序的res/raw 目录和 assets 目录下,这些文件在编译的时候和其他文件一起被打包。

    需要注意的是,来自Resources和Assets 中的文件只可以读取而不能进行写的操作,下面就通过一个例子来说明如何从
Resources 和 Assets中的文件中读取信息。首先分别在res/raw 和 assets 目录下新建两个文本文件
“test1.txt”   和 “test2.txt” 用以读取,结构如下图。

   为了避免字符串转码带来的麻烦,可以将两个文本文件的编码格式设置为UTF-8。设置编码格式的方法有很多种,比较简单的一种是用 Windows 的记事本打开文本文件,在另存为对话框中编码格式选择”UTF-8″ ,如下图。

看一下运行后的效果。

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 onCreateBundle savedInstanceState) {
        super.onCreatesavedInstanceState);
        setContentViewR.layout.main);
        tv1 = TextView)findViewByIdR.id.tv1);
        tv1.setTextColorColor.RED);
        tv1.setTextSize15.0f);
        tv2 = TextView)findViewByIdR.id.tv2);
        tv2.setTextColorColor.RED);
        tv2.setTextSize15.0f);
        tv1.setTextgetFromRaw));
        tv2.setTextgetFromAssets”test2.txt”));
    }
    
    //从resources中的raw 文件夹中获取文件并读取数据
    public String getFromRaw){
        String result = “”;
            try {
                InputStream in = getResources).openRawResourceR.raw.test1);
                //获取文件的字节数
                int lenght = in.available);
                //创建byte数组
                byte[]  buffer = new byte[lenght];
                //将文件中的数据读到byte数组中
                in.readbuffer);
                result = EncodingUtils.getStringbuffer, ENCODING);
            } catch Exception e) {
                e.printStackTrace);
            }
            return result;
    }
    
    //从assets 文件夹中获取文件并读取数据
    public String getFromAssetsString fileName){
        String result = “”;
            try {
                InputStream in = getResources).getAssets).openfileName);
                //获取文件的字节数
                int lenght = in.available);
                //创建byte数组
                byte[]  buffer = new byte[lenght];
                //将文件中的数据读到byte数组中
                in.readbuffer);
                result = EncodingUtils.getStringbuffer, ENCODING);
            } catch Exception e) {
                e.printStackTrace);
            }
            return result;
    }
}

Published by

风君子

独自遨游何稽首 揭天掀地慰生平

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注