在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 努力做一个伪程序员 阅读(24858) 评论(0) 编辑 收藏 举报
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南