android解析一個本地txt文件

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章