Runtime执行多条命令 java Runtime怎样执行多条命令

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Runtime执行多条命令 java Runtime怎样执行多条命令

积极流年   2021-11-03 我要评论
想了解java Runtime怎样执行多条命令的相关内容吗,积极流年在本文为您仔细讲解Runtime执行多条命令的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:java执行命令,Runtime执行多条命令,Runtime执行命令,下面大家一起来学习吧。

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

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

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们