java执行cmd命令

/**
 * <p>
 * <a href="https://www.cnblogs.com/convict/p/15892263.html">参考1</a>
 * <a href="https://www.cnblogs.com/youmiyou/p/15779230.html">参考2</a>
 * <a href="https://www.jianshu.com/p/43ce90abb5cd">参考3</a>
 * <a href="https://www.jb51.net/article/57637.htm">cmd命令参考</a>
 * <a href="https://blog.csdn.net/zhoujing_0424/article/details/79917368">ProcessBuilder</a>
 * <a href="https://blog.csdn.net/u013256816/article/details/54603910">ProcessBuilder 和 Process</a>
 * </p>
 *
 * @author 醉瑾
 * @since 2022-07-28
 */
public class Test8 {
    public static void execCommand() {
        try {
            Runtime runtime = Runtime.getRuntime();
            // 打开任务管理器,exec方法调用后返回 Process 进程对象
            Process process = runtime.exec("cmd.exe /c start diskmgmt.msc");
            // 等待进程对象执行完成,并返回“退出值”,0 为正常,其他为异常
            int exitValue = process.waitFor();
            System.out.println("exitValue: " + exitValue);
            // 销毁process对象
            process.destroy();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void execCommandAndGetOutput() {
        try {
            Runtime runtime = Runtime.getRuntime();
            Process process = runtime.exec("cmd.exe /c netstat -aon|findstr 3306");
            // 输出结果,必须写在 waitFor 之前
            String outStr = getStreamStr(process.getInputStream());
            // 错误结果,必须写在 waitFor 之前
            String errStr = getStreamStr(process.getErrorStream());
            int exitValue = process.waitFor(); // 退出值 0 为正常,其他为异常
            System.out.println("exitValue: \n" + exitValue);
            System.out.println("outStr: \n" + outStr);
            System.out.println("errStr: \n" + errStr);
            process.destroy();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void execute(String cmd) {
        BufferedReader br = null;
        try {
            File file = new File(System.getProperty("user.dir"));
            File tmpFile = new File(System.getProperty("user.dir") + "\\temp.tmp");//新建一个用来存储结果的缓存文件
            if (!file.exists()) {
                file.mkdirs();
            }
            if (!tmpFile.exists()) {
                tmpFile.createNewFile();
            }

            ProcessBuilder pb = new ProcessBuilder().command("cmd.exe", "/c", cmd).inheritIO();
            pb.redirectErrorStream(true);//这里是把控制台中的红字变成了黑字,用通常的方法其实获取不到,控制台的结果是pb.start()方法内部输出的。
            pb.redirectOutput(tmpFile);//把执行结果输出。
            pb.start().waitFor();//等待语句执行完成,否则可能会读不到结果。

            InputStream in = new FileInputStream(tmpFile);
            br = new BufferedReader(new InputStreamReader(in, "GBK"));
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
            br.close();
            br = null;
            tmpFile.delete();// 卸磨杀驴,删除刚才的临时文件
            System.out.println("执行完成");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException 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();
    }

    public static void main(String[] args) {
        execCommand();
//        execCommandAndGetOutput();
//        execute("ping www.baidu.com");
    }
}
  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

心醉瑶瑾前

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值