Как я могу считать текстовый файл из SD-карты в Android?

Я плохо знаком с разработкой Android.

Я должен считать текстовый файл из SD-карты и дисплея тот текстовый файл. Там какой-либо путь состоит в том, чтобы просмотреть текстовый файл непосредственно в Android или иначе как я могу считать и отобразить содержание текстового файла?

63
задан Miuranga 1 July 2011 в 08:07
поделиться

1 ответ

В вашем макете вам нужно что-то для отображения текста. TextView - очевидный выбор. Таким образом, у вас будет что-то вроде этого:

<TextView 
    android:id="@+id/text_view" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"/>

А ваш код будет выглядеть так:

//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);

Это может быть в методе onCreate() вашей Activity, или где-то еще, в зависимости от того, что именно вы хотите сделать.

122
ответ дан 24 November 2019 в 16:16
поделиться
Другие вопросы по тегам:

Похожие вопросы: