JS
建一個html文件,寫個例子:
<html>
<head>
<meta charset = "UTF-8">
</head>
<body>
Input Command :<input id = "cmdValue"/></br>
<button onclick = "jsExecuteCmd();">Execute Command</button>
</body>
<script>
/**
*命令參數說明
*cmd.exe /c 是執行完dir命令後關閉命令窗口。
*cmd.exe /k 是執行完dir命令後不關閉命令窗口。
*cmd.exe /c start 會打開一個新窗口後執行dir指令,原窗口會關閉。
*cmd.exe /k start 會打開一個新窗口後執行dir指令,原窗口不會關閉。
*注意:ActiveXObject是IE獨有的對象,其他瀏覽器不兼容
*/
function jsExecuteCmd() {
var cmdValue = document.getElementById("cmdValue").value;
var cmd = new ActiveXObject("WScript.Shell");
cmd.run("cmd.exe /k " + cmdValue);
cmd = null;
}
</script>
</html>
執行效果:
(代碼中用到了ActiveXObject對象,該對象是IE獨有,其他瀏覽器不兼容)
java
package com.yoyo.yotils.yoyo.command;
import java.io.IOException;
import java.io.InputStream;
/**
* 子邏輯
* @author yoyo
* @version $Id: JavaExecuteCmd.java, v 0.1 2019年11月18日 20:00 yoyo Exp $
*/
class JavaExecuteCmd {
static void exeCmd(String command) {
try {
Process exec = Runtime.getRuntime().exec(command);
InputStream in = exec.getInputStream();
while (in.read() != -1) {
System.out.println(in.read());
}
in.close();
//exec.waitFor();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* cmd命令模式
*/
enum ExecuteType {
CLOSE_CLIENT ("cmd /c ", "執行完dir命令後關閉命令窗口"),
NOT_CLOSE_CLIENT("cmd /k ", "執行完dir命令後不關閉命令窗口"),
CLOSE_CLIENT_NEW("cmd /c start ", "會打開一個新窗口後執行dir指令,原窗口會關閉"),
NOT_CLOSE_CLIENT_NEW("cmd /k start ", "會打開一個新窗口後執行dir指令,原窗口不會關閉");
/**
* 命令模式
*/
private String command;
/**
* 命令模式解釋
*/
private String desc;
ExecuteType(String command, String desc) {
this.command = command;
this.desc = desc;
}
/**
* Getter method for property <tt>command</tt>.
*
* @return property value of command
*/
public String getCommand() {
return command;
}
/**
* Setter method for property <tt>command</tt>.
*
* @param command value to be assigned to property command
*/
public void setCommand(String command) {
this.command = command;
}
/**
* Getter method for property <tt>desc</tt>.
*
* @return property value of desc
*/
public String getDesc() {
return desc;
}
/**
* Setter method for property <tt>desc</tt>.
*
* @param desc value to be assigned to property desc
*/
public void setDesc(String desc) {
this.desc = desc;
}}
public static void main(String[] args) {
String cmd1 = "dir";
String cmd2 = "mvn package -Dmaven.skip.test=true";
String cmd3 = "java -version";
exeCmd(ExecuteType.CLOSE_CLIENT_NEW.getCommand() + cmd2);
}
}
執行效果:
(執行打jar包測試,失敗的原因是因爲路徑不對,把該文件放到項目根目錄下執行即可成功,此處只驗證cmd是否執行)