本文實例講述了Android編程實現讀取工程中的txt文件功能。分享給大家供大家參考,具體如下:
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();}傳入一個InputStream,返回其中的文本內容。
其中:
inputStreamReader = new InputStreamReader(inputStream, "gbk");
為以gbk編碼讀取內容,不同的文本文件可能編碼不同,如果出現亂碼,可能需要調整編碼
2. 下面通過一個例子講解讀取資源文件顯示在ScrollView當中:
①.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); } }}②. 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>
③.然后在工程里面新建一個assets文件夾,隨便放一個index.txt的文件在其中,運行 Ctrl+F11進行測試即可;
希望本文所述對大家Android程序設計有所幫助。
新聞熱點
疑難解答