• 在window下, Java调用执行bat脚本


    参考博客: https://www.cnblogs.com/jing1617/p/6430141.html

    最近一段时间用到了Java去执行window下的bat脚本, 这里简单记录一下:

    我这里是先判断bat脚本是否存在, 然后去决定是否执行bat脚本,

    直接上代码:

    下面是我测试的bat脚本, 就输出一句话, 把文件命令为PostStartupScript.bat:

    echo "hello word"
    package com.test;
    
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    
    public class Test {
                
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            String batPath = "C:/Philips/SIServer/PostStartupScript.bat"; // 把你的bat脚本路径写在这里
            File batFile = new File(batPath);
            boolean batFileExist = batFile.exists();
            System.out.println("batFileExist:" + batFileExist);
            if (batFileExist) {
                callCmd(batPath);
            }
        }
        
        private static void  callCmd(String locationCmd){
            StringBuilder sb = new StringBuilder();
            try {
                Process child = Runtime.getRuntime().exec(locationCmd);
                InputStream in = child.getInputStream();
                BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(in));
                String line;
                while((line=bufferedReader.readLine())!=null)
                {
                    sb.append(line + "
    ");
                }
                   in.close();
                try {
                    child.waitFor();
                } catch (InterruptedException e) {
                    System.out.println(e);
                }
                System.out.println("sb:" + sb.toString());
                System.out.println("callCmd execute finished");           
            } catch (IOException e) {
                System.out.println(e);
            }
         }
    }

    运行结果如下:

    batFileExist:true
    sb:
    D:TestJava>echo "hello word" 
    "hello word"
    
    callCmd execute finished

    这里是在不打开任何窗口下运行的, 非常适合那些在后台需要执行bat脚本的程序.

    如果想让程序打开窗口去运行bat脚本, 可以使用如下的命令:

    java的Runtime.getRuntime().exec(commandStr)可以调用执行cmd指令.
    
    cmd /c dir 是执行完dir命令后关闭命令窗口.
    cmd /k dir 是执行完dir命令后不关闭命令窗口.
    cmd /c start dir 会打开一个新窗口后执行dir指令, 原窗口会关闭.
    cmd /k start dir 会打开一个新窗口后执行dir指令, 原窗口不会关闭.

    例如下图, 输入 cmd /k start C:/Philips/SIServer/PostStartupScript.bat
    然后会弹出新的窗口, 执行bat脚本.

     
  • 相关阅读:
    主从热备+负载均衡(LVS + keepalived)
    这12行代码分分钟让你电脑崩溃手机重启
    Linux 下虚拟机——Virtual Box
    软件著作权登记证书申请攻略
    ecshop整合discuz教程完美教程
    NetHogs——Linux下按进程实时统计网络带宽利用率
    深入研究CSS
    SSH远程会话管理工具
    nginx防止SQL注入规则
    mysql完美增量备份脚本
  • 原文地址:https://www.cnblogs.com/xumBlog/p/11064109.html
Copyright © 2020-2023  润新知