0

我在 Application 的子类中有一个方法,需要从文本文件中读取信息。我在 Activity 的子类中使用了这个方法,它工作得很好。

InputStream is = this.getResources().openRawResource(R.raw.elements);
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String str = reader.readLine();

但是,如果我在 Application 子类中使用此代码,则会出现空指针异常。

文本文件位于 res/raw 文件夹中。

4

1 回答 1

0
    private String readTxt() {

    InputStream inputStream = getResources().openRawResource(R.raw.elements);

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

    int i;
    try {
        i = inputStream.read();
        while (i != -1) {
            byteArrayOutputStream.write(i);
            i = inputStream.read();
        }
        inputStream.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return byteArrayOutputStream.toString();
}

完美运行,来源:在 /res/raw 中显示文本文件

于 2012-05-28T20:17:20.437 回答