【Java/shell】Java使用Runtime和Process调用dos命令


【需求】

使用java调用dos命令并取得输出

【代码】

package com.hy.lab.shell1;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class PingTest {
    public static void main(String[] args) throws Exception{
        Runtime runtime = Runtime.getRuntime();
        Process prcs= runtime.exec("cmd /c ping www.163.com && dir");

        BufferedReader bufReader = new BufferedReader(new InputStreamReader(prcs.getInputStream(), "GBK"));
        String line = null;
        while ((line = bufReader.readLine()) != null) {
            System.out.println(line);
        }

        int errCode = prcs.waitFor();
        System.out.println("Exited with error code:" + errCode);
    }
}

【输出】

正在 Ping z163picipv6.v.bsgslb.cn [111.31.45.165] 具有 32 字节的数据:
来自 111.31.45.165 的回复: 字节=32 时间=36ms TTL=51
来自 111.31.45.165 的回复: 字节=32 时间=28ms TTL=51
来自 111.31.45.165 的回复: 字节=32 时间=28ms TTL=51
来自 111.31.45.165 的回复: 字节=32 时间=45ms TTL=51

111.31.45.165 的 Ping 统计信息:
    数据包: 已发送 = 4,已接收 = 4,丢失 = 0 (0% 丢失),
往返行程的估计时间(以毫秒为单位):
    最短 = 28ms,最长 = 45ms,平均 = 34ms
 驱动器 C 中的卷没有标签。
 卷的序列号是 0400-647E

 C:\Users\ufo\IdeaProjects\dataMigration 的目录

2022/03/16  08:13              .
2022/03/16  08:13              ..
2022/03/21  09:08              .idea
2022/03/16  08:13             2,205 pom.xml
2022/03/15  20:51              src
2022/03/16  03:34              target
               1 个文件          2,205 字节
               5 个目录 400,011,489,280 可用字节
Exited with error code:0

Process finished with exit code 0

【参考资料】

END

相关