import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Scanner;
import javax.swing.JFrame;
/***
* @author bin
*/
public class MyCmd extends JFrame {
private static final long serialVersionUID = 1L;
private Process process;
private static PrintWriter out;
private static String command;
public MyCmd() {
try {
this.process = Runtime.getRuntime().exec("cmd");
out = new PrintWriter(process.getOutputStream());
new ConsoleIntercepter(process.getInputStream()).start();
new ConsoleIntercepter(process.getErrorStream()).start();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception, Exception,
Exception, Exception {
new MyCmd();
while (true) {
Scanner input = new Scanner(System.in);
command = input.nextLine();
if (command.equals(""))
return;
out.println(command);
out.flush();
}
}
}
class ConsoleIntercepter extends Thread {
private InputStream is;
public ConsoleIntercepter(InputStream is) {
this.is = is;
}
@Override
public void run() {
byte[] buf = new byte[1024];
int size;
while (true) {
try {
while ((size = is.read(buf)) != -1) {
System.out.print(new String(buf, 0, size, "gbk"));
}
} catch (IOException e) {
e.printStackTrace();
break;
}
}
}
}
没看明白为何程序会一直往下执行。
当构造方法执行后开启了两个线程,但之后并未再执行Runtime.getRuntime().exec("cmd");啊,
怎么会返回cmd里面的内容呢?
另一个原因是没有关闭流
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Scanner;
import javax.swing.JFrame;
/***
* @author bin
*/
public class MyCmd extends JFrame {
private static final long serialVersionUID = 1L;
private Process process;
private static PrintWriter out;
private static String command;
public MyCmd() {
try {
this.process = Runtime.getRuntime().exec("cmd");
out = new PrintWriter(process.getOutputStream());
new ConsoleIntercepter(process.getInputStream()).start();
new ConsoleIntercepter(process.getErrorStream()).start();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception, Exception,
Exception, Exception {
new MyCmd();
while (true) {
Scanner input = new Scanner(System.in);
command = input.nextLine();//这里获取你的输入
if (command.equals("")){
return;
out.println(command);//这里将你的输入输出到cmd,即作为cmd输入
out.flush();
}
}
}