I'm trying to open a Json file which is in the raw folder inside res My file structure
我正在尝试打开一个Json文件,它位于res我文件结构中的原始文件夹中
But it fails with every method I have tried, I just need the string since I can parse Json
Strings
already.
但是我尝试的每一种方法都失败了,我只需要字符串,因为我已经可以解析Json Strings了。
This is my Json
reader
这是我的Json读者
public class Parser extends Activity {
public String getStringFromJson(String path) {
StringBuffer sb = new StringBuffer();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(getAssets().open(path)));
String temp;
while ((temp = br.readLine()) != null)
sb.append(temp);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close(); // stop reading
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
It fails in the line:
它失败了:
br = new BufferedReader(new InputStreamReader(getAssets().open(path)));
br = new BufferedReader(new InputStreamReader(getAssets()。open(path)));
And this is what logcat said:
这就是logcat所说的:
02-03 10:44:13.440 2374-2374/com.example.ealcazar.kolibry E/AndroidRuntime: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ealcazar.kolibry/com.example.ealcazar.kolibry.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void java.io.BufferedReader.close()' on a null object reference
is there an easier way to read a Json
? what Path should I use when trying to access my file in the RAW folder
?
有没有更简单的方法来阅读Json?尝试访问RAW文件夹中的文件时,我应该使用什么路径?
Thank you very much.
非常感谢你。
1 个解决方案
#1
3
Replace these line of code
替换这些代码行
br = new BufferedReader(new InputStreamReader(getAssets().open(path)));
With these
br = new BufferedReader(new InputStreamReader(getResources().openRawResource(R.raw.json));//Here json is the name of the file which is placed inside the RAW folder in yours resource
#1
3
Replace these line of code
替换这些代码行
br = new BufferedReader(new InputStreamReader(getAssets().open(path)));
With these
br = new BufferedReader(new InputStreamReader(getResources().openRawResource(R.raw.json));//Here json is the name of the file which is placed inside the RAW folder in yours resource