Android:读取文本文件并存储到ArrayList<String>中

5

我正在尝试在Android中从文件中读取内容。虽然我已经初始化了一切,但仍然遇到NullPointerException。我是否漏掉了什么?

错误出现在第25行

public class Read {
    private ArrayList<String> contents;
    private final String filename = "saves/user.txt";

    public Read(Context context) {
        try {
            contents = new ArrayList<String>();
            InputStream in = context.getAssets().open(filename);

            if (in != null) {
                // prepare the file for reading
                InputStreamReader input = new InputStreamReader(in);
                BufferedReader br = new BufferedReader(input);
                String line = br.readLine();
                while (line != null) {
                    contents.add(line);
                }
                in.close();
            }else{
                System.out.println("It's the assests");
            }

        } catch (IOException e) {
            System.out.println("Couldn't Read File Correctly");
        }
    }

    public ArrayList<String> loadFile() {
        return this.contents;
    }
}

1
完整的错误堆栈跟踪怎么样? - Rahul
1
你的 br.readLine() 不在循环中。 - Oneb
line不为空时,while (line != null) { contents.add(line); } 将会运行一个无限循环。 - Mordechai
1个回答

4

请按照以下步骤操作

 while ((line=reader.readLine()) != null) 
 {
    contents.add(line);
 }

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