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("
");
            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();

        }

 参考:stackoverflow

  •  = CR(回车)→在X之前的Mac OS中用作换行符
  •  = LF(换行)→在Unix / Mac OS X中用作换行符
  •  = CR + LF→在Windows中用作换行符
如有错误,恳求读者指出,发送到wu13213786609@outlook.com。
原文地址:https://www.cnblogs.com/WLCYSYS/p/14759718.html