先上代码
Process p = Runtime.getRuntime().exec(cmdlines);
String line;
BufferedReader input =new BufferedReader(new InputStreamReader(p.getInputStream()));
//读取屏幕输出
while ((line = input.readLine()) != null) {
System.out.println("java print:"+line);
}
//关闭输入流
input.close();
我想问下为什么这个只能获取系统级别的CMD命令 比如 PING,我执行JAVA -VERSION就获取不到结果呢
汗那...给你提供个思路啊...你自己一点都不想一下的吗...
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.printStackTrace();
}
}
}
}