2011-08-24 183 views
18

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

我是否必须使用TextSwitcher或其他? 我该怎么做?

回答

31

你标记为“Android的资产,”所以我会假设你的文件是在资产的文件夹。这里:

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

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(); 
} 
+0

你从哪里得到'openFileInput()' - 方法?另外,你应该总是使用“try/finally”块来关闭流(所以当异常抛出时它们会关闭)。 –

+1

正确的方法,但是你使用了C风格的条件,它不会编译。 '不允许自动从空/整型/赋值等转换为布尔型,所以'if(instream)'和'while(line = buffreader.readLine())'需要替换为'if(instream!= null )'和'while(buffreader.hasNext())' –

+1

BufferedReader没有hasNext()函数,只是检查它是否为空 –

0

您只需使用一个TextView和ButtonView。使用BufferedReader读取文件,它将为您提供一个很好的API来逐一读取行。点击按钮,通过使用settext来改变文本视图的文本。

您也可以考虑阅读所有文件内容并将其放入字符串列表中,如果您的文件不太大,则可以更清晰。

问候, 斯特凡