您好,欢迎来到尚车旅游网。
搜索
您的当前位置:首页在window下,Java调用执行bat脚本

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

来源:尚车旅游网
在window下,Java调⽤执⾏bat脚本

参考博客:

最近⼀段时间⽤到了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:truesb:

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

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- sceh.cn 版权所有 湘ICP备2023017654号-4

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务