Home > AI > Language > Java >

read local json to string (method 2)

Example:

String fileName = "asq/asq-1.json";
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
String filePath = classLoader.getResource(fileName).getFile();
System.out.println(filePath);

try {
   File jsonFile = new File(filePath);
   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);
   }
    reader.close();
    String jsonStr = sb.toString();
    System.out.println(jsonStr);
} catch (IOException e) {
    e.printStackTrace();
}

Leave a Reply