您的位置:首页 > 移动开发 > Android开发

android从asset文件夹读取文件

2014-02-08 09:21 260 查看
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();
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: