分享

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

 black library 2011-10-30
下面通过一个例子讲解读取资源文件显示在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./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进行测试即可;
分享到:

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约