前言
由于系统对命令的空格分隔符会截断错误,因此对长指令如ls -al /
最好不要用String传入,而是使用String[] cmd = {"ls", "-al", "/"}
用字符串数组的形式传入
直调执行cmd、shell命令
无需回显
不要回显只是运行直接exec即可
String[] cmd = {"calc"};
Runtime.getRuntime.exec(cmd);
需要回显、输出返回值
回显返回值需要获取InputStream,然后reader读取输入流可以指定编码(例如Windows下cmd默认是GBK,不设置编码可能有乱码出现),之后再按行读取缓冲区显示即可
public static void main(String[] args) throws Exception {
String[] cmd = {"ls", "-al", "."};
InputStream is = Runtime.getRuntime().exec(cmd).getInputStream();
InputStreamReader isr = new InputStreamReader(is, "UTF-8");
BufferedReader br = new BufferedReader(isr);
String line = br.readLine();
while (line != null){
System.out.println(line);
line = br.readLine();
}
}
反射执行命令
这里对传入的指令类型String和String[]的处理不同,不需要回显只到invoke即可
以String传入指令
反射获取构造器和类方法exec,然后invoke,输出
package Test;
import java.io.InputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
public class ReflectRuntime {
public static void main(String[] args) throws Exception {
String cmd = "whoami";
Class cls = Class.forName("java.lang.Runtime");
Constructor constructor = cls.getDeclaredConstructor();
constructor.setAccessible(true);
Object obj = constructor.newInstance();
Method method = cls.getDeclaredMethod("exec", String.class);
Process p = (Process) method.invoke(obj, cmd);
InputStream is = p.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = br.readLine();
while (line != null){
System.out.println(line);
line = br.readLine();
}
}
}
以String[]传入指令
注意method.invoke(obj, (Object) cmd);
,需要将cmd向上转型为Object才能传入
package Test;
import java.io.InputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
public class ReflectRuntime {
public static void main(String[] args) throws Exception {
String[] cmd = {"ls", "-al", "."};
Class cls = Class.forName("java.lang.Runtime");
Constructor constructor = cls.getDeclaredConstructor();
constructor.setAccessible(true);
Object obj = constructor.newInstance();
Method method = cls.getDeclaredMethod("exec", String[].class);
Process p = (Process) method.invoke(obj, (Object) cmd);
InputStream is = p.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = br.readLine();
while (line != null){
System.out.println(line);
line = br.readLine();
}
}
}
完
欢迎在评论区留言,欢迎关注我的CSDN @Ho1aAs