日期:2014-05-19 浏览次数:20847 次
import java.io.*;
import java.nio.*;
public class Test {
public static void main(String[] args) throws IOException {
new Test().testConsole();
}
private Process p = null;
public void testConsole() {
try {
p = Runtime.getRuntime().exec("cmd");
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
new ConsoleReturn(p.getInputStream()).start();
new ConsoleReturn(p.getErrorStream()).start();
new ConsoleOutput(p.getOutputStream()).start();
}
private class ConsoleOutput extends Thread {
private OutputStream os;
public ConsoleOutput(OutputStream os) {
this.os = os;
}
@Override
public void run() {
InputStream console = System.in;
InputStreamReader reader = null;
try {
reader = new InputStreamReader(console,"GBK");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
BufferedReader br = new BufferedReader(reader);
String cmd;
PrintWriter pw = new PrintWriter(os);
while(true) {
try {
cmd = br.readLine();
} catch (IOException e) {
e.printStackTrace();
break;
}
if(cmd.equals("exit")) {
break;
} else {
pw.println(cmd);
pw.flush();
}
}
pw.close();
}
}
private class ConsoleReturn extends Thread {
private InputStream is;
public ConsoleReturn(InputStream is) {
this.is = is;
}
@Override
public void run() {
InputStreamReader reader = null;
try {
reader = new InputStreamReader(is,"GBK");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
char[] buf = new char[1024];
int size;
while(true) {
try {
size = reader.read(buf);
} catch (IOException e) {
e.printStackTrace();
break;
}
if(size != -1) {
System.out.print(new String(buf,0,size));
} else {
break;
}
}
try {
reader.close();
} catch (IOException e) {
e.