如何逐行读取文件

18

我有一个包含文本的文件,每行都是独立的。
我希望先显示第一行,然后如果我按下一个按钮,第二行应该显示在TextView中,而第一行应该消失。然后,如果我再次按下按钮,第三行应该被显示,以此类推。

我应该使用TextSwitcher还是其他什么东西?我该如何做到这一点?

3个回答

31

你将它标记为 "android-assets",因此我假设你的文件在 assets 文件夹中。这里:

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/button1

另外:出于空间考虑,此处几乎没有错误检查。您需要检查您的资产是否存在,我非常确定当您打开文件进行读取时应该有一个try/catch块。

编辑:重大错误,它不是R.layout,而是R.id 我已经编辑了我的答案以解决问题。


1
如果答案对您有帮助,您还可以通过接受答案来获得声望。 - Otra

16

以下代码应该满足您的需求

try {
// open the file for reading
InputStream instream = new FileInputStream("myfilename.txt");

// if file the available for reading
if (instream != null) {
  // prepare the file for reading
  InputStreamReader inputreader = new InputStreamReader(instream);
  BufferedReader buffreader = new BufferedReader(inputreader);

  String line;

  // read every line of the file into the line-variable, on line at the time
  do {
     line = buffreader.readLine();
    // do something with the line 
  } while (line != null);

}
} catch (Exception ex) {
    // print stack trace.
} finally {
// close the file.
instream.close();
}

дҪ д»Һе“ӘйҮҢиҺ·еҸ–openFileInput()ж–№жі•пјҹжӯӨеӨ–пјҢдҪ еә”иҜҘе§Ӣз»ҲдҪҝз”ЁвҖңtry/finallyвҖқеқ—жқҘе…ій—ӯжөҒпјҲиҝҷж ·е®ғ们еңЁжҠӣеҮәејӮеёёж—¶е°ұдјҡиў«е…ій—ӯпјүгҖӮ - Lukas Knuth
1
正确的方法,但您使用了 C 风格的条件,这将无法编译。Java 不允许从 null/int/assignment 等自动转换为布尔值,因此 if (instream)while ( line = buffreader.readLine() ) 需要替换为类似于 if (instream != null)while( buffreader.hasNext() ) 的内容。 - epochengine
1
BufferedReader没有hasNext()函数。只需检查它是否为null即可。 - Error 454

0
你可以简单地使用TextView和ButtonView。使用BufferedReader读取文件,它将为您提供一个很好的API来逐行读取。在按钮上单击时,只需使用settext更改textview的文本即可。
如果您的文件不太大,您还可以考虑读取所有文件内容并将其放入字符串列表中,这样可以更清晰。
问候, Stéphane

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接