package testproject;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
public class TestProcess {
static SystemIn input;
static SystemOut output;
static SystemErr errput;
static Process process;
public static void main(String[] args) throws Exception{
ProcessBuilder processBuilder=new ProcessBuilder("cmd");
process=processBuilder.start();
input=new SystemIn(process.getInputStream());
output=new SystemOut(process.getOutputStream());
errput=new SystemErr(process.getErrorStream());
input.start();
output.start();
errput.start();
int i=process.waitFor();
System.out.println(i);
//TODO 通过NIO来实现子线程的关闭
System.exit(0);
}
static int stopProcess() {
System.out.println(process.exitValue());
return process.exitValue();
}
static class SystemIn extends Thread{
boolean flag=true;
InputStream in;
public SystemIn(InputStream in) {
super();
this.in = in;
}
public InputStream getIn() {
return in;
}
public void setIn(InputStream in) {
this.in = in;
}
@Override
public void run() {
InputStreamReader reader = null;
try {
reader = new InputStreamReader(in,"GBK");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
int i;
while(flag){
try {
if((i=reader.read())!=-1)
System.out.print((char)i);
} catch (IOException e) {
e.printStackTrace();
break;
}
}
}
}static class SystemOut extends Thread{
boolean flag=true;
OutputStream out;
public SystemOut(OutputStream out) {
super();
this.out = out;
}
public OutputStream getOut() {
return out;
}
public void setOut(OutputStream out) {
this.out = out;
}
@Override
public void run() {
while(flag){
try {
char c=(char) System.in.read();
out.write(c);
if(c==10)
out.flush();
} catch (IOException e) {e.printStackTrace();
break;
}
}
}
}static class SystemErr extends Thread{
InputStream err;
public SystemErr(InputStream err) {
super();
this.err = err;
}
public InputStream getErr() {
return err;
}
public void setErr(InputStream err) {
this.err = err;
}
@Override
public void run() {
boolean flag=true;
InputStreamReader reader = null;
try {
reader = new InputStreamReader(err, "GBK");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
int i;
while(flag){
try {
if((i=reader.read())!=-1)
System.err.print((char)i);
} catch (IOException e) {
e.printStackTrace();
break;
}
}
}
}
}
通过java实现windows命令行的衔接