JAVA 读写JSON文件

时间:2025-02-14 22:09:42
关于读写读写JSON文件,我这里推荐一个github上面starts18k的开源项目Hutool

这是Hutool文档地址 /docs/#/

下面我们来实际操作一下

首先我们配置文件

        <dependency>
            <groupId></groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.4.4</version>
        </dependency>
  • 1
  • 2
  • 3
  • 4
  • 5

更新一下maven之后我们开始使用hutool对json文件进行读写

    public void allUpdatesPlayed() {
        String dataVhfJson = ResourceUtil.readUtf8Str("json/device/vhf/data_vhf.json");
        List<DataVhfEntity> dataVhfEntities = JSONArray.parseArray(dataVhfJson, DataVhfEntity.class);
        if (ObjectUtil.isNull(dataVhfEntities)) {
            return;
        }
        dataVhfEntities.forEach(dataVhfEntity -> dataVhfEntity.setStatus(1));
        JSONArray jsonArray = new JSONArray();
        jsonArray.addAll(dataVhfEntities);
        FileWriter fileWriter = new FileWriter("json/device/vhf/data_vhf.json");
        fileWriter.write(jsonArray.toString());
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

我们解析一下上面的源码
首先ResourceUtil提供了资源快捷读取封装
我们文件放在了src/resources/json/device/vhf目录下,则读取路径入下

String dataVhfJson = ResourceUtil.readUtf8Str("json/device/vhf/data_vhf.json");
  • 1

注意:在IDEA中,新加入文件到src/resources目录下,需要重新import项目,以便在编译时顺利把资源文件拷贝到target目录下。如果提示找不到文件,请去target目录下确认文件是否存在。

后面的代码对读取出来的数据进行一系列操作之后我们再写入到文件中去

FileWriter fileWriter = new FileWriter("json/device/vhf/data_vhf.json");
fileWriter.write(jsonArray.toString());
  • 1
  • 2

写入文件分为追加模式和覆盖模式两类,追加模式可以用append方法,覆盖模式可以用write方法。

这样我们就完成了对JSON的读取和写入了