zoukankan      html  css  js  c++  java
  • 在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脚本.

     
  • 相关阅读:
    LG P4449 & JZOJ 于神之怒
    [国家集训队]Crash的数字表格
    LG P3768 简单的数学题
    NOI2018 屠龙勇士
    为什么从后台获取的id到前端后却变了?Long类型转json时前端js丢失精度解决方案-----@JsonSerialize和@JsonDeserialize
    vue的filters过滤器优化
    根据key查询redis中是否存在key对应的value,根据key获取值
    PowerDesigner逆向工程将MYSQL数据库转成pdm
    解决图片验证码不显示的问题
    报错:Unknown column 'province' in 'field list'
  • 原文地址:https://www.cnblogs.com/xumBlog/p/11064109.html
Copyright © 2011-2022 走看看