借这个机会好好再温习一下JSON
本地读取JSON文件,实际上主要是:三个痛点
壹、 JSON文件的放置的目录(即文件路径,简单说:放在[Resource]目录下)
Resource不仅仅是文件名,而且是需要被 Mark Direcotory As “resource root”
贰、JSON解析后的变量数据格式要保持一致
叁、读取文件的工具及写法(两种):
第一种写法:
InputStream is = null;
InputStreamReader isr = null;
BufferedReader br = null;
try {
Resource resource = resourceLoader.getResource(file);
is = resource.getInputStream();
isr = new InputStreamReader(is);
br = new BufferedReader(isr);
String url;
while((url = br.readLine()) != null) {
if(!StringUtils.isEmpty(url)){
initApi.add(url.trim());
}
}
// 打印文件内容 用以验证
}catch (Exception e){
// 加载失败处理
}finally {
if(br != null){br.close();}
if(isr != null){isr.close();}
if(is != null){is.close();}
}
===============我是简单的分割线===============
第一种写法:(此方法来自文尾参考的博客)
String jsonStr = "";
try {
File jsonFile = new File(fileName);
FileReader fileReader = new FileReader(jsonFile);
Reader reader = new InputStreamReader(new FileInputStream(jsonFile),"utf-8");
int ch = 0;
StringBuffer sb = new StringBuffer();
while ((ch = reader.read()) != -1) {
sb.append((char) ch);
}
fileReader.close();
reader.close();
jsonStr = sb.toString();
return jsonStr;
} catch (IOException e) {
e.printStackTrace();
return null;
}