Java 生成和读取JSON文件

下面的demo当中 ,是将json文件放到了zip包当中。如果不需要,可以拿掉。

1、生成对象JSON文件

	public static void crateJson() {
        try {

            String orcPath = "D:\\doc\\ts_service_orchestration.json";
            // 对象集合或者对象都可以
            List<DataPO> dataPOList = new ArrayList<>();
            String jsonString = JSONObject.toJSONString(dataPOList);
            // 生成json文件
            tempFile(orcPath, jsonString);

            FileInputStream fileInputStream = null;
            int length;
            byte[] b = new byte[1024];
            int len;
            String path =  "D:\\doc\\压缩包.zip";
            File zipfile = new File(path);
            if (!zipfile.exists()) {
                zipfile.createNewFile();
            }

            // 将json文件放入到压缩包当中
            // key 文件名称, value 文件地址
            HashMap<String, String> maps = new HashMap<>();
            maps.put("ts_service_orchestration.json", orcPath);
            ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile));
            for (Map.Entry<String, String> entry : maps.entrySet()) {
                File newFile = new File(entry.getValue());
                fileInputStream = new FileInputStream(newFile);
                out.putNextEntry(new ZipEntry(entry.getKey()));

                while ((len = fileInputStream.read(b)) > 0)
                {
                    out.write(b, 0, len);
                }
                out.closeEntry();
                fileInputStream.close();
            }
            out.close();

            // delete jsonFile
            new File(orcPath).delete();

        }catch (Exception e){
            e.printStackTrace();
        }
    }

	public static void tempFile(String filePath, String jsonData) throws IOException {
        // 保证创建一个新文件
        File file = new File(filePath);
        if (!file.getParentFile().exists()) { // 如果父目录不存在,创建父目录
            file.getParentFile().mkdirs();
        }
        if (file.exists()) { // 如果已存在,删除旧文件
            file.delete();
        }
        file.createNewFile();

        // 格式化json字符串
        jsonData = JsonUtil.formatJson(jsonData);

        // 将格式化后的字符串写入文件
        Writer write = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
        write.write(jsonData);
        write.flush();
        write.close();
    }

2、读取json文件

	public static void readJson(){
        try {
            // 转为压缩文件流
            ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream("D:\\doc\\压缩包.zip"), Charset.forName("gbk"));
            ZipEntry zipEntry = null;

            while ((zipEntry = zipInputStream.getNextEntry()) != null) {
                if (!zipEntry.isDirectory() && zipEntry.getName().endsWith(".json")) {
                    // Read the Excel file from the Zip entry
                    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                    byte[] buffer = new byte[4096];
                    int length = -1;
                    while ((length = zipInputStream.read(buffer)) != -1) {
                        outputStream.write(buffer, 0, length);
                    }
                    outputStream.close();
                    tempReadFile(outputStream);
                    zipInputStream.closeEntry();
                }
            }
            zipInputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

	public static void tempReadFile(ByteArrayOutputStream outputStream) throws IOException {
        String jsonStr = "";
        Reader reader = new InputStreamReader(new ByteArrayInputStream(outputStream.toByteArray()),"utf-8");
        int ch = 0;
        StringBuffer sb = new StringBuffer();
        while ((ch = reader.read()) != -1) {
            sb.append((char) ch);
        }
        reader.close();
        jsonStr = sb.toString();
        // 这里注意,如果是json文件当中是对象集合的话可以这样写,但是如果是对象的话,这样转换是会出错的。
        JSONArray array = JSONObject.parseArray(jsonStr);
        for (Object o : array) {
            JSONObject jsonObject = (JSONObject)o;
            System.out.println(jsonObject);
        }
        System.out.println("=================================================================");
    }

你可能感兴趣的:(工具类,java,json,开发语言)