1, first create a new folder under Res named Raw, add a TXT file below it;
2, create a layout file, a button above the starting point to hit the event, the following a textview display text information;
3, obtain content through a inputstream;
XML Layout Code:
<?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 code:
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 {
/**
* Get content from a 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 ();
}
/**
* Get its content through the path to the TXT file
*
* @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);
}
}
Code Demo:
http://download.csdn.net/detail/weimo1234/8734255
android resolves a local txt file