Java实现CURL,与把字符串结果写到json文件

@Override
    public String getUrlRestInfo(String[] command, String fileName) {
        //新建一个StringBuffer
        StringBuffer sb = new StringBuffer();
        //过程
        Process pro = null;
        try {
            //执行命令
            pro = Runtime.getRuntime().exec(command);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //
        assert pro != null;
        BufferedReader br = new BufferedReader(new InputStreamReader(pro.getInputStream()), 4096);
        String line = null;
        int i = 0;
        //先读取每行的数据
        while (true) {
            try {
                if (!((line = br.readLine()) != null)) break;
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (0 != i)
                sb.append("\r\n");
            i++;
            sb.append(line);
        }
//        System.out.println(sb.toString());
//       return JSON.parseObject(sb.toString());
        //调用接口,然后写到文件里

        try {
            writeToText(sb.toString(), fileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    /**
     * 读取字符串,生成txt 文件 已解决未设置编码时,在项目中直接打开文件,中文乱码问题
     * WriteText.writeToText(musicInfo,fileName)直接调用
     *
     *
     */
        public static void writeToText(String musicInfo, String fileName) throws IOException {
            // 生成的文件路径
//            String path = "G:\\data\\" + fileName + ".txt";
            String path = "C:\\Users\\dell\\IdeaProjects\\yarnalert\\src\\main\\resources" + fileName + ".json";
            File file = new File(path);
            if (!file.exists()) {
                file.getParentFile().mkdirs();
            }
            file.createNewFile();
            // write 解决中文乱码问题
            // FileWriter fw = new FileWriter(file, true);
            OutputStreamWriter fw = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(musicInfo);
            bw.flush();
            bw.close();
            fw.close();

        }

 

上一篇:spring boot 下载单个文件与文件夹打包为zip下载


下一篇:SSM整合中易出现的问题(xml文件无法自动加载,跨域,lib目录,乱码等)