zoukankan      html  css  js  c++  java
  • 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。
  • 相关阅读:
    【转】JS模块化工具requirejs教程(二):基本知识
    【转】JS模块化工具requirejs教程(一):初识requirejs
    【转】批处理命令 For循环命令详解!
    【转】NodeJS教程--基于ExpressJS框架的文件上传
    【转】WebSocket 是什么原理?为什么可以实现持久连接?
    网页工具地址
    【转】DataURL在Web浏览器中的兼容性总结
    侯捷STL学习(一)--顺序容器测试
    strstr-strcat实现
    算法设计与分析
  • 原文地址:https://www.cnblogs.com/WLCYSYS/p/14759718.html
Copyright © 2011-2022 走看看