public static void main(String[] args) {
try {
exec(new String[]{
"cmd.exe",
"/C",
"java"
});
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 运行cmd命令
*/
public static boolean exec(String[] cmdAry) throws Exception {
Runtime rt = Runtime.getRuntime();
Process proc = null;
try {
proc = rt.exec(cmdAry);
/*
* Runtime的exec()方法类似线程,不会在cmd命令执行完成后再继续运行下面的代码,
* 所以导致可能cmd命令还没执行完毕,程序就运行到了Process的destroy()方法,因
* 此需要一个方法去等待cmd命令执行完毕后,再运行exec()之后的方法
*/
return waitForProcess(proc) > 0;
} finally {
if (proc != null) {
proc.destroy();
proc = null;
}
}
}
/**
* 得到cmd命令返回的信息数据流,该流的运行周期与cmd命令的实行时间相同
*/
public static int waitForProcess(Process proc) throws Exception {
// cmd命令有返回正确的信息流,和错误信息流,不过不能绝对表示cmd命令是否执行正确
BufferedReader in = null;
BufferedReader err = null;
String msg = null;
int exitValue = -1;
try {
in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
while ((msg = in.readLine()) != null) {
System.out.println(msg);
if (1 != exitValue) {
exitValue = 1;
}
}
err = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
while ((msg = err.readLine()) != null) {
System.out.println(msg);
if (0 != exitValue) {
exitValue = 0;
}
}
return exitValue;
} finally {
if (null != in) {
in.close();
in = null;
}
if (null != err) {
err.close();
err = null;
}
}
}
java执行cmd命令
最新推荐文章于 2025-03-17 20:47:41 发布