我如何能够逐行读取.txt文件

时间:2014-03-03 10:16:08

标签: character line

我在SD卡上有一个文件 - “file.txt”,其中包含单独行中的电话号码。 我想首先显示行,然后如果我按下一个按钮,第二行应该显示在TextView中,第一行应该消失。 我的代码只是读取txt文件的内容并完全插入TextView中的所有行:

当您按下按钮????

时,如何将此代码更改为串行输出以下行?
    File sdcard = Environment.getExternalStorageDirectory();
    File file = new File(sdcard,"file.txt");
    StringBuilder text = new StringBuilder();
        try {
        BufferedReader br = new BufferedReader(new FileReader(file));
        String line;

        while ((line = br.readLine()) != null) {
            line = br.readLine();
            text.append(line);
            text.append('\n');
        }
    }
    catch (IOException e) {
    }
    tv.setText(text);

当您按下按钮????

时,如何将此代码更改为串行输出以下行?

1 个答案:

答案 0 :(得分:0)

您可以将文件的内容存储在ArrayList<串GT; ,然后,在按下按钮时,将TextView中的文本更改为列表中的另一个文本。类似的东西:

  1. 读取文件并存储在列表中:

    //make this a class member variable
    List<String> numbers = new ArrayList<String>();
    
    while((line = br.readLine()) != null) {
        //store each line in our list as separate entry
        numbers.add(line);
    }
    
  2. 按下按钮时更新TextView:

    //make this a class member variable
    //this is being used to get the line from list
    int currentLine = 0;
    
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //set the text
            tv.setText(numbers.get(currentLine));
    
            //increment currentLine
            currentLine++;
    
            //make sure we don't go beyond the number of lines stored in the list
            //so if we reach the last index, we start from the beginning
            if (currentLine == numbers.size()) {
                currentLine = 0;
            }
        }
    });