如何获得文件中读取一行一行 [英] How to get file read line by line

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

问题描述

我有一个包含在单独的行文本文件。
我想首先显示行,然后如果我preSS一个按钮,第二行应显示在的TextView 键,第一行应该消失。然后,如果我preSS一遍,第三行应显示等。

I have a file containing text in separate line.
I want to display line first, and then if I press a button, the second line should be displayed in the TextView and the first line should disappear. Then, if I press it again, the third line should be displayed and so on.

我是否应该使用 TextSwitcher 或别的什么吗? 我该怎么办呢?

Should I have to use TextSwitcher or anything else? How can I do that?

推荐答案

您已被标签为Android的资产,所以我会假设你的文件是在资产的文件夹中。这里:

You tagged it as "android-assets" so I'm going to assume your file is in the assets folder. Here:

InputStream in;
BufferedReader reader;
String line;
TextView text;

public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    text = (TextView) findViewById(R.id.textView1);
    in = this.getAssets().open(<your file>);
    reader = new BufferedReader(new InputStreamReader(in));
    line = reader.readLine();

    text.setText(line);
    Button next = (Button) findViewById(R.id.button1);
    next.setOnClickListener(this);
}

public void onClick(View v){
    line = reader.readLine();
    if (line != null){
        text.setText(line);
    } else {
        //you may want to close the file now since there's nothing more to be done here.
    }
}

试试这个。我一直没能验证它的工作原理完全,但我相信这是你要遵循的总体思路。当然你要更换任何 R.id.textView1 /按钮1 与您在布局文件中所指定的名称。

Give this a try. I haven't been able to verify that it works completely, but I believe this is the general idea you want to follow. Naturally you'll want to replace any R.id.textView1/button1 with the names that you've specified in your layout file.

另外:很少有错误检查这里为了节省空间。您将要检查是否存在你的资产,我是pretty的肯定应该有一个的try / catch 块,当你打开文件进行读取。

Also: There is very little error checking here for the sake of space. You will want to check that your asset exists and I'm pretty sure there should be an try/catch block when you open the file for reading.

编辑:大错误,这不是 R.layout ,它是 R.id 我已经编辑我的答案来解决这个问题。

Big error, It's not R.layout, it's R.id I have edited my answer to fix the problem.

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

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