【问题标题】:How to get file read line by line如何逐行读取文件
【发布时间】:2011-11-02 18:15:29
【问题描述】:

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

我应该使用TextSwitcher 还是其他什么? 我该怎么做?

【问题讨论】:

    标签: android android-assets readfile


    【解决方案1】:

    您将其标记为“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我已经编辑了我的答案来解决这个问题。

    【讨论】:

    • 如果对您有帮助,您也可以通过接受答案来获得声誉。
    【解决方案2】:

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

    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”-block 来关闭流(因此当抛出异常时它们会被关闭)。
    • 正确的方法,但是您使用了无法编译的 C 风格条件。 Java 不允许从 null/int/assignment 等自动转换为布尔值,因此需要将 if (instream)while ( line = buffreader.readLine() ) 替换为 if (instream != null)while( buffreader.hasNext() ) 之类的东西
    • BufferedReader 没有 hasNext() 函数。只需检查它是否为空。
    【解决方案3】:

    您可以简单地使用 TextView 和 ButtonView。使用 BufferedReader 读取文件,它将为您提供一个很好的 API 来逐行读取。单击按钮时,只需使用 settext 更改 textview 的文本。

    您还可以考虑读取所有文件内容并将其放入字符串列表中,如果您的文件不太大,这会更干净。

    问候, 斯蒂芬

    【讨论】:

      猜你喜欢
      • 2011-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多