建设银行开户行地址:如何读取assets文件夹中的txt文件

来源:百度文库 编辑:中财网 时间:2024/04/25 02:50:25
2010-06-20

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

    博客分类:
  • Android(网络相关)
AndroidJavaOSXML下面通过一个例子讲解读取资源文件显示在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.   
  2.     xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_height="fill_parent" android:paddingTop="50dip">   
  4.     
  5.         android:layout_height="wrap_content" android:textStyle="normal" />   
  6.   


3.然后在工程里面新建一个assets文件夹,随便放一个index.txt的文件在其中,运行
  Ctrl+F11进行测试即可;
分享到: 如何获取屏幕分辨率 | 横、竖屏幕动态切换(layout-land 和layout ...