Android:读取文本文件并存储到ArrayList <string> </string>

时间:2013-03-08 03:25:26

标签: java android string arraylist

所以我试图从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 个答案:

答案 0 :(得分:3)

这样做

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