六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 44|回复: 0

如何读取assets文件夹中的txt文件

[复制链接]

升级  35.2%

212

主题

212

主题

212

主题

进士

Rank: 4

积分
676
 楼主| 发表于 2013-1-15 02:26:41 | 显示全部楼层 |阅读模式
下面通过一个例子讲解读取资源文件显示在ScrollView当中:
1.ReadAsset.java文件:
package com.example.ReadAsset;import android.app.Activity;import android.os.Bundle;import android.widget.TextView;import java.io.IOException;import java.io.InputStream;public class ReadAsset extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.read_asset);try {//Return an AssetManager instance for your application's packageInputStream is = getAssets().open("index.txt");int size = is.available();// Read the entire asset into a local byte buffer.byte[] buffer = new byte[size];is.read(buffer);is.close();// Convert the buffer into a string.String text = new String(buffer, "GB2312");// Finally stick the string into the text view.TextView tv = (TextView) findViewById(R.id.text);tv.setText(text);} catch (IOException e) {// Should never happen!throw new RuntimeException(e);}}}
2. read_asset.xml文件
<?xml version="1.0" encoding="utf-8"?><ScrollView android:layout_width="fill_parent"xmlns:android="http://schemas.android.com/apk/res/android"android:layout_height="fill_parent" android:paddingTop="50dip"><TextView android:id="@+id/text" android:layout_width="fill_parent"android:layout_height="wrap_content" android:textStyle="normal" /></ScrollView>

3.然后在工程里面新建一个assets文件夹,随便放一个index.txt的文件在其中,运行
  Ctrl+F11进行测试即可;
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表