In your layout bạn sẽ cần thứ gì đó để hiển thị văn bản. A TextView
là sự lựa chọn hiển nhiên. Vì vậy, bạn sẽ có một cái gì đó như thế này:
<TextView
android:id="@+id/text_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
Và mã của bạn sẽ trông như thế này:
//Find the directory for the SD Card using the API
//*Don't* hardcode "/sdcard"
File sdcard = Environment.getExternalStorageDirectory();
//Get the text file
File file = new File(sdcard,"file.txt");
//Read text from file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
br.close();
}
catch (IOException e) {
//You'll need to add proper error handling here
}
//Find the view by its id
TextView tv = (TextView)findViewById(R.id.text_view);
//Set the text
tv.setText(text);
Điều này có thể đi vào các phương pháp onCreate()
của Activity
của bạn, hoặc ở một nơi khác tùy thuộc vào chỉ là những gì nó là bạn muốn làm.
Nguồn
2010-05-25 09:27:12
bạn có muốn biết làm thế nào để viết một chương trình mà đọc một file txt hoặc bạn có muốn biết làm thế nào để làm nó như một người sử dụng? – SteelBytes