Java 读取src目录下的json文件

时间:2022-11-01 09:14:53

直接上代码,但是有个乱码的地方需要特殊转码一下。

/**
     * 读取json文件,返回json串
     * @param fileName
     * @return
     */
    private String readJsonFile(String fileName) {
    	String jsonStr = "";
    	try {
    		File jsonFile = ResourceUtils.getFile("classpath:"+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;
		}
	}