打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
如何读取assets文件夹中的txt文件
下面通过一个例子讲解读取资源文件显示在ScrollView当中:
1.ReadAsset.java文件:
Java代码
 
  1. package com.example.ReadAsset;   
  2.   
  3. import android.app.Activity;   
  4. import android.os.Bundle;   
  5. import android.widget.TextView;   
  6. import java.io.IOException;   
  7. import java.io.InputStream;   
  8.   
  9. public class ReadAsset extends Activity {   
  10.     @Override  
  11.     protected void onCreate(Bundle savedInstanceState) {   
  12.         super.onCreate(savedInstanceState);   
  13.         setContentView(R.layout.read_asset);   
  14.   
  15.         try {   
  16. //Return an AssetManager instance for your application's package   
  17.             InputStream is = getAssets().open("index.txt");   
  18.             int size = is.available();   
  19.   
  20.             // Read the entire asset into a local byte buffer.   
  21.             byte[] buffer = new byte[size];   
  22.             is.read(buffer);   
  23.             is.close();   
  24.   
  25.             // Convert the buffer into a string.   
  26.             String text = new String(buffer, "GB2312");   
  27.   
  28.             // Finally stick the string into the text view.   
  29.             TextView tv = (TextView) findViewById(R.id.text);   
  30.             tv.setText(text);   
  31.         } catch (IOException e) {   
  32.             // Should never happen!   
  33.             throw new RuntimeException(e);   
  34.         }   
  35.     }   
  36. }  

2. read_asset.xml文件
Java代码
 
  1. <?xml version="1.0" encoding="utf-8"?>   
  2. <ScrollView android:layout_width="fill_parent"  
  3.     xmlns:android="http://schemas.android.com/apk/res/android"  
  4.     android:layout_height="fill_parent" android:paddingTop="50dip">   
  5.     <TextView android:id="@+id/text" android:layout_width="fill_parent"  
  6.         android:layout_height="wrap_content" android:textStyle="normal" />   
  7. </ScrollView>  


3.然后在工程里面新建一个assets文件夹,随便放一个index.txt的文件在其中,运行
  Ctrl+F11进行测试即可;
分享到:
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Android 设置TextView滑动滚动条和滑动效果
android中关于scrollview内部组件android:layout
android实现TextView垂直或水平滚动 | 萝卜白菜的小站
Android开发笔记(八)— 样式化的对象,Style样式的定义
listview怎样设置每个Item的高度?
Android中用TextView显示大量文字的方法
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服