1,首先在res下面新建一个名字为raw的文件夹,添加一个txt文件在其下面;
2,创建一个布局文件,上面一个按钮出发点击事件,下面一个textview显示文本信息;
3,通过一个InputStream获取内容;
xml布局代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="@+id/button1"
android:layout_width="fill_parent"
android:layout_height="147dp"
android:text="Button" />
<ScrollView
android:id="@+id/scrollView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:id="@+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:id="@+id/textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
</ScrollView>
</LinearLayout>
java代码:
1,
public class ReaderDemoActivity extends Activity {
Button button;
TextView textView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button = (Button) findViewById(R.id.button1);
textView = (TextView) findViewById(R.id.textView1);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
InputStream inputStream = getResources().openRawResource(R.raw.shi);
String string = TxtReader.getString(inputStream);
textView.setText(string);
}
});
}
}
2,
public class TxtReader {
/**
* 通过一个InputStream获取内容
*
* @param inputStream
* @return
*/
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();
}
/**
* 通过txt文件的路径获取其内容
*
* @param filepath
* @return
*/
public static String getString(String filepath) {
File file = new File(filepath);
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return getString(fileInputStream);
}
}
代码demo下载地址:
http://download.csdn.net/detail/weimo1234/8734255