0 前言
本篇文章总结一下java命令执行的三种方式,并且测试了在win环境一次方法调用中可同时执行多个命令的方式。
1 java.lang.Runtime
public class RuntimeTest {
public static void test1() throws IOException{
Runtime runtime = Runtime.getRuntime();
runtime.exec(new String[]{"cmd", "/c", "calc", "&", "notepad"});
}
public static void test2() throws IOException{
Runtime runtime = Runtime.getRuntime();
runtime.exec("cmd /c calc & notepad");
}
public static void test3() throws IOException{
Runtime runtime = Runtime.getRuntime();
runtime.exec("cmd.exe /k calc & notepad");
}
public static void test4() throws IOException{
Runtime runtime = Runtime.getRuntime();
runtime.exec(new String[]{"cmd.exe", "/k", "calc", "&", "notepad"});
}
public static void test5() throws IOException {
Runtime runtime = Runtime.getRuntime();
Process start = runtime.exec("ping www.baidu.com");
InputStream inputStream = start.getInputStream();
byte[] res = new byte[1024];
inputStream.read(res);
System.out.println(new String(res, "gbk"));
}
public static void main(String[] args) throws IOException {
test2();
}
}
2 java.lang.ProcessBuilder
public class ProcessBuilderTest {
public static void test1() throws IOException {
ProcessBuilder processBuilder = new ProcessBuilder("cmd.exe", "/c", "calc", "&", "notepad");
Process start = processBuilder.start();
}
public static void test2() throws IOException {
ProcessBuilder processBuilder = new ProcessBuilder("cmd.exe", "/k", "calc", "&", "notepad");
Process start = processBuilder.start();
}
public static void main(String[] args) throws IOException {
test1();
}
}
3 java.lang.ProcessImpl
通过调试ProcessBuilder.start()方法发现,其底层调用了ProcessImpl.start()方法:
但是ProcessImpl类不是public的,因此无法在java.lang包外使用,需要通过反射的方式使用:
public class ProcessImplTest {
public static void main(String[] args) throws Exception{
Class clazz = Class.forName("java.lang.ProcessImpl");
Method start = clazz.getDeclaredMethod("start", String[].class, Map.class, String.class, ProcessBuilder.Redirect[].class, boolean.class);
start.setAccessible(true);
start.invoke(null, new String[]{"calc"}, null, null, null, false);
}
4 javax.script.ScriptEngineManager
这种方式本质还是使用的上面三种方式:
public class EvalTest {
public static void main(String[] args) throws ScriptException {
Object result = new ScriptEngineManager().getEngineByExtension("js").eval("java.lang.Runtime.getRuntime().exec(\"calc\")");
System.out.println(result);
}
}