1.众所周知,Android的res文件夹是用来存储资源的,可以在res文件夹下建立一个raw文件夹,放置在raw文件夹下的内容会被原样打包,而不会被编译成二进制文件,并且可以通过R文件进行很方便地访问。
比如我们可以将更新信息、版权信息等放到txt文件中,然后放到raw文件中,然后很方便地进行访问。
在raw中放入一个a.txt文件,然后就可以在Activity中使用getResources().openRawResource(R.raw.a);方法获取一个此文件的InputStream类,而后就可以很方便地进行读写a.txt了。
- InputStream inputStream = getResources().openRawResource(R.raw.a);
一个获取InputStream中字符串内容的方法:
- public static String getString(InputStream inputStream) {
- InputStreamReader inputStreamReader = null;
- try {
- inputStreamReader = new InputStreamReader(inputStream, "gbk");
- } catch (UnsupportedEncodingException e1) {
- e1.printStackTrace();
- }
- BufferedReader reader = new BufferedReader(inputStreamReader);
- StringBuffer sb = new StringBuffer("");
- String line;
- try {
- while ((line = reader.readLine()) != null) {
- sb.append(line);
- sb.append("\n");
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- return sb.toString();
- }
其中
- inputStreamReader = new InputStreamReader(inputStream, "gbk");
为以gbk编码读取内容,不同的文本文件可能编码不同,如果出现乱码,可能需要调整编码
/-----------------------------------------------------------
2下面通过一个例子讲解读取资源文件显示在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 {
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.read_asset);
- try {
- //Return an AssetManager instance for your application's package
- InputStream 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进行测试即可;