/**
     * 读取指定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);

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐