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("=================================================================");
    }
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java生成并下载JSON文件的过程相对简单。以下是一个基本的示例代码,可以实现这个功能: ```java import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import com.google.gson.Gson; public class JsonGenerator { public static void main(String[] args) { // 创建一个对象并设置数据 MyData myData = new MyData(); myData.setName("John"); myData.setAge(25); myData.setCity("New York"); // 将对象转换为JSON字符串 Gson gson = new Gson(); String jsonString = gson.toJson(myData); // 生成JSON文件 String filePath = "path/to/your/file.json"; try { PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(filePath))); writer.println(jsonString); writer.close(); System.out.println("JSON文件生成:" + filePath); } catch (IOException e) { e.printStackTrace(); } } } class MyData { private String name; private int age; private String city; // 省略构造函数和getter/setter方法 // 注意:为了将对象转换为JSON字符串,MyData类必须提供无参数构造函数。 MyData() {} } ``` 这段代码做了以下几件事情: 1. 创建一个`MyData`对象并设置数据。 2. 使用Gson库将该对象转换为JSON字符串。 3. 使用`BufferedWriter`和`PrintWriter`将JSON字符串写入文件。 4. 通过指定文件路径生成JSON文件。 5. 如果一切顺利,将输出文件路径。 要使用此代码,请确保在项目中添加了Gson库的依赖。 通过这段代码,你可以生成JSON文件并将其下载到用户的计算机上。但是要注意,下载的过程通常是Web应用程序的一部分,需要使用合适的HTTP响应头和Servlet API进行处理。以上代码只是生成并保存JSON文件到本地的示例,你可能需要根据实际情况进行适当的修改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值