如何逐行读取文件

Sun*_*nny 18 android readfile android-assets

我有一个文件在单独的行中包含文本.
我想首先显示行,然后如果我按下按钮,第二行应显示在TextView第一行,第一行应该消失.然后,如果我再次按下它,则应显示第三行,依此类推.

我应该使用TextSwitcher还是其他什么?我怎样才能做到这一点?

Otr*_*tra 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.
    }
}
Run Code Online (Sandbox Code Playgroud)

试一试.我无法验证它是否完全有效,但我相信这是您想要遵循的一般想法.当然,您需要R.id.textView1/button1使用您在布局文件中指定的名称替换any .

另外:为了节省空间,这里的错误检查非常少.您需要检查您的资产是否存在,并且我非常确定try/catch在您打开文件进行阅读时应该有一个块.

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


Ron*_*nie 15

以下代码应满足您的需求

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();
}
Run Code Online (Sandbox Code Playgroud)