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

相关文章
相关标签/搜索