通常由两种方法
1.方法一
try {
// 根据resource文件路径,生成文件
File jsonFile = ResourceUtils.getFile("classpath:ZhongLv.json");
// 解析文件为指定编码的字符串
// 方法实现:先将文件转inPutStream,再调用下面的IOUtils.toString()方法;
String json = FileUtils.readFileToString(jsonFile,"UTF-8");
JSONArray jsonArray = JSON.parseArray(json);
} catch (IOException e) {
e.printStackTrace();
}
2.方法二
/**
* 本系统和第三方系统字段对应关系json
*/
@Value("classpath:ZhongLv.json")
private Resource relation;
String relationStr = null;
try {
// 方法实现:将文件的InputStream写入inputStreamReader,再调用方法把reader写入writer,再使用StringBuilderWriter接收,最后toString();
relationStr = IOUtils.toString(relation.getInputStream(), StandardCharsets.UTF_8);
} catch (IOException e) {
e.printStackTrace();
}
3.总结
他们的底层都是IO操作,汇总后的IOUtils.toString方法如下
private static final int EOF = -1;
private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
public static String toString(InputStream input, Charset encoding) throws IOException {
StringBuilderWriter sw = new StringBuilderWriter();
InputStreamReader in = new InputStreamReader(input, Charsets.toCharset(encoding));
char [] buffer = new char[DEFAULT_BUFFER_SIZE];
long count = 0;
int n = 0;
while (EOF != (n = in.read(buffer))) {
sw.write(buffer, 0, n);
count += n;
}
return sw.toString();
}