最后要达到的效果是,从res/raw下一个txt文件读取里面的内容,显示到textview控件上。
写一些内容到一个txt文件,以utf-8编码格式保存该txt文件。
新建一个Activity,名称是test,在res目录下新建raw文件夹,将txt文件放入其中。
界面非常简单
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/textView"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
为了获取资源,我们要使用resources类,结构如下:
java.lang.Object | |
↳ | android.content.res.Resources |
下面是Activity,也很简单
package com.example.test;
import java.io.InputStream;
import java.util.Scanner;
import android.app.Activity;
import android.content.res.Resources;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
// 获得一个resources对象实例
Resources res = getResources();
// openRawResource方法返回一个输入流
InputStream inputStream = res.openRawResource(R.raw.book);
// 实例化scanner对象
Scanner scanner = new Scanner(inputStream);
StringBuffer sb = new StringBuffer();
// 一行一行的读取
while (scanner.hasNextLine()) {
sb.append(scanner.nextLine()).append("\n");
}
scanner.close();
textView.setText(sb);
}
}