文件流读取
通过InputStreamReader
去读取json文件。
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
public static void main(String[] args) {
File file = new File("D:\\test.json");
StringBuffer stringBuffer = new StringBuffer();
try {
InputStreamReader reader = new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8);
BufferedReader bufferedReader = new BufferedReader(reader);
bufferedReader.readLine();
int str;
while ((str = bufferedReader.read()) != -1) {
stringBuffer.append((char) str);
}
bufferedReader.close();
reader.close();
System.out.println(stringBuffer);
} catch (Exception e) {
e.printStackTrace();
}
}
hutool工具读取
使用readJSON
方法可以直接读取出json文件内容。
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
public static void main(String[] args) {
File file = new File("D:\\test.json");
try {
JSON json = JSONUtil.readJSON(file, StandardCharsets.UTF_8);
String jsonStr = json.toJSONString(1); // indentFactor每一级别的缩进
System.out.println(jsonStr);
JSONArray jsonArray = JSONUtil.parseArray(jsonStr);
ArrayList<Object> arrayList = ListUtil.toList(jsonArray);
for (Object obj : arrayList) {
Map<String, Object> map = (Map<String, Object>) obj;
System.out.println(((Map<?, ?>) obj).get("STU_ID"));
}
} catch (Exception e) {
e.printStackTrace();
}
}