Java执行cmd命令

博客 动态
0 215
羽尘
羽尘 2022-02-14 14:55:20
悬赏:0 积分 收藏

Java执行cmd命令

通常 Java 执行 Windows 或者 Linux 的命令时,都是使用 Runtime.getRuntime.exec(command) 来执行的

eg1: 执行命令

public static void execCommand() {    try {        Runtime runtime = Runtime.getRuntime();        // 打开任务管理器,exec方法调用后返回 Process 进程对象        Process process = runtime.exec("cmd.exe /c taskmgr");        // 等待进程对象执行完成,并返回“退出值”,0 为正常,其他为异常        int exitValue = process.waitFor();        System.out.println("exitValue: " + exitValue);        // 销毁process对象        process.destroy();    } catch (IOException | InterruptedException e) {        e.printStackTrace();    }}

eg2: 执行命令,并获取正常输出与错误输出

public static void execCommandAndGetOutput() {    try {        Runtime runtime = Runtime.getRuntime();        Process process = runtime.exec("cmd.exe /c ipconfig");        // 输出结果,必须写在 waitFor 之前        String outStr = getStreamStr(process.getInputStream());        // 错误结果,必须写在 waitFor 之前        String errStr = getStreamStr(process.getErrorStream());        int exitValue = process.waitFor(); // 退出值 0 为正常,其他为异常        System.out.println("exitValue: " + exitValue);        System.out.println("outStr: " + outStr);        System.out.println("errStr: " + errStr);        process.destroy();    } catch (IOException | InterruptedException e) {        e.printStackTrace();    }}public static String getStreamStr(InputStream is) throws IOException {    BufferedReader br = new BufferedReader(new InputStreamReader(is, "GBK"));    StringBuilder sb = new StringBuilder();    String line;    while ((line = br.readLine()) != null) {        sb.append(line);        sb.append("\n");    }    br.close();    return sb.toString();}

process对象可以通过操作数据流,对执行的命令进行参数输入、获取命令输出结果、获取错误结果

getInputStream()获取process进程的输出数据
getOutputStream()获取process进程的输入数据
getErrorStream()获取process进程的错误数据

值得注意的是

getInputStream() 为什么是获取输出数据?getOutputStream()为什么是获取输入数据?这是因为 input 和 output 是__针对当前调用 process 的程序而言的__,即

要获取命令的输出结果,就是被执行命令的结果 输入到我们自己写的程序中,所以用getInputStream()

要往别的程序输入数据,就是我们程序要输出,所以此时用getOutputStream()


尊重写作权利,转载请注明出处 ^_^
posted @ 2022-02-14 14:08 Convict 阅读(0) 评论(0) 编辑 收藏 举报
回帖
    羽尘

    羽尘 (王者 段位)

    2335 积分 (2)粉丝 (11)源码

     

    温馨提示

    亦奇源码

    最新会员