Java 调用bat文件并传入参数,并且不出现cmd的黑框框

来源:互联网 发布:ch是什么软件 编辑:程序博客网 时间:2024/05/08 23:54
常规调用方式:(这个肯定会弹一下黑框)

  Runtime.getRuntime().exec("cmd /c start XXX.bat");



解决不弹框只需要“start”后面加一个参数“/b”就行:

  Runtime.getRuntime().exec("cmd /c start /b XXX.bat");

 

 

import java.io.InputStream;

/**

 */

public class BatTest {

    public static void main(String[] args) {

        runbat("d:\\test.bat", "1.1.1.1", "111");

    }

 

    /** 文件路径一定不要写错了,比如没有空格之类的,因为不会报错,导致很难排查
     * 执行批处理命令  
     */
    public static void runbat(String batPath, String... argStrings) {
        String cmd = "cmd /c start /b " + batPath + " ";
        if (argStrings != null && argStrings.length > 0) {
            for (String string : argStrings) {
                cmd += string + " ";
            }
        }
        try {
            Process ps = Runtime.getRuntime().exec(cmd);
            InputStream inputStream = ps.getInputStream();
            byte[] by = new byte[1024];
//            while (inputStream.read(by) != -1) {

                  if(new String(by,"utf-8")).contains("echo success")){

break;

}
//                System.out.println(new String(by,"utf-8"));
//            }
            inputStream.close();
        } catch (Exception ioe) {
            ioe.printStackTrace();
        }
    }
}

 

如何判断bat处理命令结束。

比如在bat命令尾部加上 echo success 可以根据这个来判断命令处理完毕。

然后,跳出读取流。否则会一直处于等待状态。

 

0 0
原创粉丝点击