你把 response 里面的 run 方法改成你要的, request 里面的 run 方法是发送命令。样例中我向 request 中发送了 dir 命令,然后在 response 中得到了输出。
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class Main {
public static void main(String[] args) throws IOException {
Process shell = Runtime.getRuntime().exec("cmd.exe");
final InputStream input = shell.getInputStream();
final OutputStream output = shell.getOutputStream();
Thread request = new Thread() {
public void run() {
try {
output.write("dir".getBytes());
} catch (Exception e) {
e.printStackTrace();
}
}
};
request.start();
Thread response = new Thread() {
public void run() {
int c = -1;
byte[] buf = new byte[512];
try {
while ((c = input.read(buf)) != -1) {
System.out.print(new String(buf, 0, c));
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
response.start();
}
}