android读取工程目录下的文件,Android编程实现读取工程中的txt文件功能
本文實例講述了Android編程實現(xiàn)讀取工程中的txt文件功能。分享給大家供大家參考,具體如下:
1. 眾所周知,Android的res文件夾是用來存儲資源的,可以在res文件夾下建立一個raw文件夾,放置在raw文件夾下的內(nèi)容會被原樣打包,而不會被編譯成二進制文件,并且可以通過R文件進行很方便地訪問。
比如我們可以將更新信息、版權(quán)信息等放到txt文件中,然后放到raw文件中,然后很方便地進行訪問。
在raw中放入一個a.txt文件,然后就可以在Activity中使用getResources().openRawResource(R.raw.a);方法獲取一個此文件的InputStream類,而后就可以很方便地進行讀寫a.txt了。
InputStream inputStream = getResources().openRawResource(R.raw.a);
一個獲取InputStream中字符串內(nèi)容的方法:
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,返回其中的文本內(nèi)容。
其中:
inputStreamReader = new InputStreamReader(inputStream, "gbk");
為以gbk編碼讀取內(nèi)容,不同的文本文件可能編碼不同,如果出現(xiàn)亂碼,可能需要調(diào)整編碼
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文件
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="fill_parent" android:paddingTop="50dip">
android:layout_height="wrap_content" android:textStyle="normal" />
③.然后在工程里面新建一個assets文件夾,隨便放一個index.txt的文件在其中,運行 Ctrl+F11進行測試即可;
希望本文所述對大家Android程序設計有所幫助。
總結(jié)
以上是生活随笔為你收集整理的android读取工程目录下的文件,Android编程实现读取工程中的txt文件功能的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 花草香背景能换什么
- 下一篇: android 可折叠标题栏,ViewP