2

我真的不知道这有什么问题,我想逐行读取 txt 文件(目前只有 10行)并将每一行存储在一些名为 mChoices 的数组列表中。

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.quiz_vieaaaw);
        try {
            InputStream inputStream = getApplicationContext().getAssets().open("questions.txt");
            BufferedReader buffReader = new BufferedReader(new InputStreamReader(inputStream));
            String line = buffReader.readLine();
            while (line != null) {
            mChoices.add(line);
            }
            inputStream.close();
        } 
        catch (IOException e) {
            e.printStackTrace();
        }
        for (int i=0; i < mChoices.size(); i++) {
            String line = mChoices.get(i);
            Log.d("LINE", line);
        }
    }

}

我在分配 13571696 字节时出现内存不足。

如果我在条件下注释掉它只返回第一行,但显然我想要 txt 中的每一行。

谢谢

4

1 回答 1

5
while (line != null) {
     mChoices.add(line);
 }

您每次都需要更新该行,否则您将始终读取第一行(在您的情况下这不是空的,因此您将在第一行写入无限次,直到有可用内存为止)。
要在每次迭代时更新该行,请执行以下操作:

String line;
while ((line = buffReader.readLine()) != null) {
        mChoices.add(line);
}
于 2013-06-10T15:43:14.297 回答