最後要達到的效果是,從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);
}
}