如何将文件分配给 InputStream?
How to assign File to InputStream?
之前我从 android 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 File(getActivity().getExternalFilesDir(null), "jsonfile.json");
之前我从 android 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 File(getActivity().getExternalFilesDir(null), "jsonfile.json");