Android 如何将文件分配给InputStream?
之前我从androidAndroid 如何将文件分配给InputStream?,android,fileinputstream,Android,Fileinputstream,之前我从androidresources的raw文件夹中读取了一个json文件 InputStream inputStream = getResources().openRawResource(R.raw.jsonfile); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); int ctr; try { ctr = inputStrea
resources
的raw
文件夹中读取了一个json文件
InputStream inputStream = getResources().openRawResource(R.raw.jsonfile);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int ctr;
try {
ctr = inputStream.read();
while (ctr != -1) {
byteArrayOutputStream.write(ctr);
ctr = inputStream.read();
}
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
JSONObject jObject = null;
try {
jObject = new JSONObject(
byteArrayOutputStream.toString());
} catch (JSONException e) {
e.printStackTrace();
}
Gson g = new Gson();
MyList responseData = g.fromJson(jObject.toString(), MyList.class);
if (responseData.getPeopleList().size() == 0) {
//do something
}
现在我需要将该文件保存在设备的外部存储器中。我试着代替上面的第一行
File fileJson = new File(getActivity().getExternalFilesDir("/folderName"), "jsonfile.json");
InputStream inputStream = null;
try {
inputStream = new FileInputStream(fileJson);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
但是现在responseData
现在为空。请纠正我
错误日志为
java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
步骤1:将文件放入您认为是Android/data/myappfolder/files/
的文件中。因此,您将拥有Android/data/myappfolder/files/jsonfile.json
步骤2:使用
File fileJson=new文件(getActivity().getExternalFilesDir(null),“jsonfile.json”)
/folder
不是传递给getExternalFilesDir()
的参数的有效值。除此之外,“这没有像我预期的那样起作用”是什么意思?“你的症状是什么?”Commonware详细阐述了我的问题。请现在再次检查,/folder
不是getExternalFilesDir()
的有效值。您试图加载的文件在哪里?来自我设备的外部存储(“Android/data/myappfolder”),但我使用了文件fileJson=new file(getActivity().getExternalFilesDir(“/folderName”),“jsonfile.json”);fileJson.createNewFile();创建该文件