代码实现
public static void multiWx(String wxPath) throws IOException {
Runtime runtime = Runtime.getRuntime();
String[] command = {"cmd","/c","start","\"\"",wxPath};
System.out.println(String.join(" ", Arrays.asList(command)));
InputStream inputStream = runtime.exec(command).getInputStream();
try (InputStreamReader inputStreamReader = new InputStreamReader(inputStream)) {
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line = bufferedReader.readLine();
while(line!=null){
System.out.println(line);
}
}
}
public static void main(String[] args) throws IOException {
multiWx("X:\\Tencent\\WeChat\\WeChat.exe");
}
Java调用命令是以文件句柄的形式调用,Java并没有获取到shell,因此这里需要从cmd.exe调用,指令为
cmd /c dir
。同理,Linux下需要执行/bin/sh -c xxx
/c
表示运行结束后关闭cmd.exe,另外/k
表示不关闭
修改commad可以执行其他cmd命令