java 操作文件的读取与写入 json格式数据

/**
     * 读取指定ID对应的文件内容。
     *
     * @param id 文件ID,用于构造文件名。
     * @return 文件的内容作为字符串,如果文件不存在则返回空字符串。
     */
    private static String readFileContent(String id) {
        String fileName = "workapi_" + id + ".json";
        String filePath = "src/main/resources/data/workapi/" + fileName;
        Path path = Paths.get(filePath);

        // 检查文件是否存在
        if (!Files.exists(path)) {
            System.err.println("文件不存在: " + filePath);
            return "";
        }

        StringBuilder contentBuilder = new StringBuilder();

        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String currentLine;
            while ((currentLine = br.readLine()) != null) {
                contentBuilder.append(currentLine);
            }
        } catch (IOException e) {
            System.err.println("无法读取文件: " + filePath);
            e.printStackTrace();
            return null; // 或者可以根据需求抛出异常
        }

        return contentBuilder.toString();
    }

private static void createJSONFile(String content, String id) {
        String fileName = "workapi_" + id + ".json";

        try (BufferedWriter writer = new BufferedWriter(new FileWriter("src/main/resources/data/workapi/" + fileName))) {
            writer.write(content);
            writer.newLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

// 调用写入

String jsonResponse  = response.substring(25,response.length()-1);
                // System.out.println(jsonResponse);
                Gson gson1 = new Gson();
                CateData = gson1.fromJson(jsonResponse, new TypeToken<Response>(){}.getType());
                System.out.println(CateData.getTitle());

                createJSONFile(jsonResponse, id);

// 读取
String readFileContent = readFileContent(id);

  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值