Android读取资源文件

最后要达到的效果是,从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
Class for accessing an application's 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);
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值