我怎样才能读取SD卡中的Andr​​oid的文本文件? [英] How can I read a text file from the SD card in Android?

查看:123
本文介绍了我怎样才能读取SD卡中的Andr​​oid的文本文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新的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 <一个href="http://developer.android.com/intl/de/reference/android/widget/TextView.html"><$c$c>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.

这篇关于我怎样才能读取SD卡中的Andr​​oid的文本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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