读取文件内容

@Scheduled(cron = "0 0/1 * * * ?")
public void task() {
    //执行该命令
    List<String> commands= new ArrayList<>();
    commands.add("cd /home/mysql_bak");
    commands.add("cat bak.log");
    List<String> list = executeNewFlow(commands);
    logger.info("得到备份执行结果数据:" + list);
}


public List<String> executeNewFlow(List<String> commands) {
    List<String> rspList = new ArrayList<String>();
    Runtime run = Runtime.getRuntime();
    try {
        Process proc = run.exec("/bin/bash", null, null);
        BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
        PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(proc.getOutputStream())), true);
        for (String line : commands) {
            logger.info("执行命令:" + line);
            out.println(line);
        }
        // 这个命令必须执行,否则in流不结束。
        out.println("exit");
        String rspLine = "";
        logger.info("返回结果:BufferedReader" + in.readLine());
        while ((rspLine = in.readLine()) != null) {
            System.out.println(rspLine);
            logger.info("返回结果:" + rspLine);
            rspList.add(rspLine);
        }
        proc.waitFor();
        in.close();
        out.close();
        proc.destroy();
    } catch (IOException e1) {
        e1.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return rspList;
}

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐