android从asset文件夹读取文件

1)将一个txt文本(msg.txt)复制到开发目录的asset文件夹下。

2)用getAssets().open()可以得到一个输入流。注意getAssets方法必须用在Activity下边。如果不是一个activity而只是一个普通class,则要将context传递到class里,然后再用getAssets()。

public myClass(Context myContext) {
    AssetManager mngr = myContext.getAssets();
    InputStream is = mngr.open("textdb.txt");
}

3)得到inputstream可以做自己想做的事了。比如转化成string然后改变textview。

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView tv= (TextView)findViewById(R.id.textid);
        
        InputStream input;
        try{
            input= getAssets().open("msg.txt");
            int size= input.available();
            byte[] buffer= new byte[size];
            input.read(buffer);
            input.close();
            String text = new String(buffer);
            tv.setText(text);
        }catch(IOException e){
            e.printStackTrace();
        }
        
        
        
        
    }

 

posted @ 2014-02-08 09:21  zmiao  阅读(1308)  评论(0编辑  收藏  举报