1.定义一个工具类 public static String readJsonFile(String filePath) { String jsonStr = ""; try { File jsonFile = new File(filePath); Reader reader = new InputStreamReader(new FileInputStream(jsonFile), StandardCharsets.UTF_8); int ch = 0; StringBuilder sb = new StringBuilder(); while ((ch = reader.read()) != -1) { sb.append((char) ch); } reader.close(); jsonStr = sb.toString(); return jsonStr; } catch (Exception ex) { ex.printStackTrace(); return null; } }
2.使用时在方法里直接调用该工具类 参数里添加文件的具体路径
//根据文件路径获取文件 读取json,返回一个字符串 String jsonStr = JsonUtil.readJsonFile("D:/files/student-class.json"); //转化成json数组 JSONArray result = JSONObject.parseArray(jsonStr);