我怎样才能读取SD卡中的Andr​​oid的文本文件?文本文件、SD、Andr、oid

由网友(浪漫,她,我,爱)分享简介:我是新的Andr​​oid开发。I am new to Android development.我需要读取SD卡中的文本文件,并显示该文本文件。有没有什么方法可以直接在Android或其他人我怎么可以读取并显示一个文本文件的内容查看的文本文件?I need to read a text file from th...

我是新的Andr​​oid开发。

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?

推荐答案

在布局你需要一些东西来显示文本。 A 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"/>

和你的code将是这样的:

And your code will look like this:

//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()方法取决于究竟有什么是你想做的事。

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

阅读全文

相关推荐

最新文章