在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 + "\n");
            }
               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脚本.

 

 

 

posted on 2019-06-21 13:46  努力做一个伪程序员  阅读(23949)  评论(0编辑  收藏  举报

导航