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

参考博客: http://www.javashuo.com/article/p-rqmdjems-cg.htmlhtml

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

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

直接上代码:测试

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

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);
        }
     }
}

运行结果以下:spa

batFileExist:true
sb:
D:\TestJava>echo "hello word" 
"hello word"

callCmd execute finished

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

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

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脚本.

相关文章
相关标签/搜索