欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

java Runtime如何执行多条命令

时间:2022-02-27 09:21:08|栏目:JAVA代码|点击:

java Runtime如何执行多条命令

使用 && 分隔命令

public static void cmd()  {
        String ls = "  cd /home/ &&  dir ";
        Process process = null;
        String cmd = getOsCmd()+ ls;
        try {
            process = Runtime.getRuntime().exec(cmd);
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                System.out.println(new String(line.getBytes(),"GBK"));
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        finally {
            process.destroy();
        }
    }
 
    public static String getOsCmd(){
        Properties props=System.getProperties(); //获得系统属性集
        String osName = props.getProperty("os.name"); //操作系统名称
        if(osName.toLowerCase().contains("linux")){
            return "/bin/sh -c";
        }else if(osName.toLowerCase().contains("windows")){
            return "cmd /c";
        }else{
            throw new RuntimeException("服务器不是linux|windows操作系统");
        }
    }

Runtime.getRuntime().exec 执行多条

中间加上 & 或者 && 就可以执行多条了.

Runtime.getRuntime().exec("cmd1 && " +
"cmd2 && " +
"cmd3 && " );

上一篇:写了两年代码之后再来谈一谈Spring中的Bean

栏    目:JAVA代码

下一篇:springboot+WebMagic+MyBatis爬虫框架的使用

本文标题:java Runtime如何执行多条命令

本文地址:http://www.codeinn.net/misctech/194655.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有