• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

java Runtime如何执行多条命令

java 搞代码 4年前 (2022-01-09) 21次浏览 已收录 0个评论
文章目录[隐藏]

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.getPr<b>本文来源gao@!dai!ma.com搞$$代^@码!网</b>operty("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 && " );

以上为个人经验,希望能给大家一个参考,也希望大家多多支持搞代码


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:java Runtime如何执行多条命令
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址