用Java修改json文件的内容(读取文件修改后输出)

关于json格式,java主要有二种解析方式(还有一种谷歌的解析用的比较少):

1、net.sf.json.JSONObject

2、com.alibaba.fastjson.JSONObject

对于第一种和第二种有一个区别就是格式化json的时候,是否会改变对象的顺序。

下面是一段修改json文件的代码,采用第一种方式,为了保持原json顺序不变,大概思路就是将haisdb对象中的数据库连接(端口和地址):统一改为"host":"hais_db","port":3306,

json内容:

{
  "haisdb": {
    "readonly":false,
    "client": "mysql",
    "connection": {
      "host": "155.155.1.177",
      "user": "root",
      "password": "123456",
      "timezone": "0800",
      "database": "hais"
    },
    "timezone": "+08:00",
    "pool": {
      "min": 1,
      "max": 10
    },
    "acquireConnectionTimeout": 10800000
  },
  "redis": {
    "host": "155.155.1.177",
    "db": 0
  }
}

 

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import net.sf.json.JSONObject;

import java.io.*;

public class UpdateJson {

    public static void main(String[] args) {
        String filePath = null;
        File file = null;
        if (args.length == 1){
            filePath =args[0];
            file = new File(filePath);
        } else {
            //filePath = "D:\\updateJson\\db.json";
            //file = new File(filePath);
            System.out.println("请输入要修改的db.json路径,退出码1");
            System.exit(1);
        }
        if (!file.exists()){
            System.out.println("该路径下没有db.json,程序异常退出,退出码1");
            System.exit(1);
        }
        try {
            //JSONObject jsonObject = JSON.parseObject(new FileInputStream(file), JSONObject.class);
            String content = readFileByLines(filePath);
            JSONObject jsonObject = JSONObject.fromObject(content);
            System.out.println("程序开始读取db.json");
            //获取haisdb对象
            Object haisdb = jsonObject.get("haisdb");
            //删除hais对象
            jsonObject.remove("haisdb");

            JSONObject haisdbJson = JSONObject.fromObject(haisdb);
            //获取connection对象
            String connection = haisdbJson.getString("connection");

            //删除connection对象
            haisdbJson.remove("connection");

            JSONObject connectinJson = JSONObject.fromObject(connection);

            connectinJson.put("host","hais_db");
            connectinJson.put("port",3306);

            haisdbJson.put("connection",connectinJson);
            jsonObject.put("haisdb",haisdbJson);

            Object redis = jsonObject.get("redis");
            if (redis != null){
                jsonObject.remove("redis");
                JSONObject redisJson = JSONObject.fromObject(redis);
                redisJson.put("host","hais_redis");
                redisJson.put("port","6379");
                jsonObject.put("redis",redisJson);
            }

            String pretty = JSON.toJSONString(jsonObject,
                    SerializerFeature.PrettyFormat,
                    SerializerFeature.WriteMapNullValue,
                    SerializerFeature.WriteDateUseDateFormat);

            BufferedWriter bw = new BufferedWriter(new FileWriter(filePath));
            bw.write(pretty);
            bw.flush();
            bw.close();
            System.out.println("程序正常退出,退出码0");
            System.exit(0);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String readFileByLines(String fileNmae){
        BufferedReader reader = null;
        String content = "";
        String tempString = null;
        try {
            reader = new BufferedReader(new FileReader(new File(fileNmae)));
            while ((tempString = reader.readLine()) != null){
                content += tempString;
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            if (reader != null){
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return content;
    }
}

 

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
你可以使用Java自带的ZipFile和ZipOutputStream类来实现修改压缩包里的json文件。下面是一个简单的代码示例: ```java import java.io.*; import java.util.zip.*; public class ModifyJsonInZipFile { public static void main(String[] args) throws IOException { // 定义读取的压缩包路径 String zipFilePath = "path/to/your/zip/file.zip"; // 定义写入的压缩包路径 String modifiedZipFilePath = "path/to/your/modified/zip/file.zip"; // 定义要修改json文件名 String jsonFileName = "example.json"; // 定义要修改json文件内容 String newJsonContent = "{\"name\": \"John\", \"age\": 30}"; // 创建读取压缩包的ZipFile对象 ZipFile zipFile = new ZipFile(zipFilePath); // 创建写入压缩包的ZipOutputStream对象 ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(modifiedZipFilePath)); // 遍历压缩包里的每一个条目 for (ZipEntry entry : zipFile) { // 如果条目是要修改json文件 if (entry.getName().equals(jsonFileName)) { // 创建新的ZipEntry对象,用于写入新的json内容 ZipEntry newEntry = new ZipEntry(entry.getName()); // 将新的ZipEntry对象添加到ZipOutputStream中 zipOutputStream.putNextEntry(newEntry); // 将新的json内容写入ZipOutputStream中 zipOutputStream.write(newJsonContent.getBytes()); // 关闭当前条目的输出流 zipOutputStream.closeEntry(); } else { // 如果条目不是要修改json文件,直接将其添加到ZipOutputStream中 zipOutputStream.putNextEntry(entry); InputStream inputStream = zipFile.getInputStream(entry); byte[] buffer = new byte[1024]; int len; while ((len = inputStream.read(buffer)) > 0) { zipOutputStream.write(buffer, 0, len); } zipOutputStream.closeEntry(); } } // 关闭ZipOutputStream和ZipFile对象 zipOutputStream.close(); zipFile.close(); } } ``` 在这个示例中,我们首先定义了要读取的压缩包路径、要写入的压缩包路径、要修改json文件名和要修改json文件内容。然后,我们创建了一个ZipFile对象来读取压缩包里的条目,创建了一个ZipOutputStream对象来写入修改后的压缩包。接着,我们遍历了每一个条目,如果条目是要修改json文件,就创建一个新的ZipEntry对象,将新的json内容写入ZipOutputStream中;如果条目不是要修改json文件,就直接将其添加到ZipOutputStream中。最后,我们关闭了ZipOutputStream和ZipFile对象。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值