[英]Android - Reading text File from Application subclass
I have a method in a subclass of Application that needs to read information from a text file. 我在Application的子类中有一个需要从文本文件中读取信息的方法。 I have used this method in a subclass of Activity and it worked fine.
我在Activity的子类中使用了此方法,并且效果很好。
InputStream is = this.getResources().openRawResource(R.raw.elements);
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String str = reader.readLine();
However this gives a null pointer exception if I use this code in the Application subclass. 但是,如果我在Application子类中使用此代码,则会给出空指针异常。
the text file is in the res/raw folder. 文本文件位于res / raw文件夹中。
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();
}
Works Perfectly, Source : Display text file in /res/raw 完美工作,来源: 在/ res / raw中显示文本文件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.