public jsonResult callCmd(String locationCmd) {
jsonResult result = new jsonResult();
BufferedReader br = null;
try {
File file = new File(“D:\daemonTmp”);
File tmpFile = new File(“D:\daemonTmp\temp.tmp”);//新建一个用来存储结果的缓存文件
if (!file.exists()){
file.mkdirs();
}
if(!tmpFile.exists()) {
tmpFile.createNewFile();
}
ProcessBuilder pb = new ProcessBuilder().command(“cmd.exe”, “/c”, locationCmd).inheritIO();
pb.redirectErrorStream(true);//这里是把控制台中的红字变成了黑字,用通常的方法其实获取不到,控制台的结果是pb.start()方法内部输出的,简直就像是自欺欺人。
pb.redirectOutput(tmpFile);//把执行结果输出。
pb.start().waitFor();//等待语句执行完成,否则可能会读不到结果。
InputStream in = new FileInputStream(tmpFile);
br= new BufferedReader(new InputStreamReader(in));
String line = null;
while((line = br.readLine()) != null) {
System.out.println(line);
java执行CMD命令调用外部程序会直接运行完毕
最新推荐文章于 2022-08-31 10:34:23 发布