如何从 Android 中的 SD 卡读取文本文件? [英] How can I read a text file from the SD card in Android?

查看:39
本文介绍了如何从 Android 中的 SD 卡读取文本文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Android 开发新手.

I am new to Android development.

我需要从 SD 卡读取文本文件并显示该文本文件.有什么办法可以直接在Android中查看文本文件,或者如何读取和显示文本文件的内容?

I need to read a text file from the SD card and display that text file. Is there any way to view a text file directly in Android or else how can I read and display the contents of a text file?

推荐答案

在你的布局中,你需要一些东西来显示文本.TextView 是显而易见的选择.所以你会有这样的事情:

In your layout you'll need something to display the text. A TextView is the obvious choice. So you'll have something like this:

<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('
');
    }
    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);

这可以在您的 ActivityonCreate() 方法中,或其他地方,具体取决于您想要做什么.

This could go in the onCreate() method of your Activity, or somewhere else depending on just what it is you want to do.

这篇关于如何从 Android 中的 SD 卡读取文本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆