How to execute a command prompt command & view output in Java
- By Abhinav Kar on May 25, 2009
- Java
The basic part is very easy. To do this, we will use the Runtime’s exec method. The code would be like:
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("ping localhost");
The command (I’ve used “ping localhost” ) can be anything that your command prompt recognizes. It will vary on UNIX and Windows environment.
Now comes the bit where you would want to see the output of the execution. This I handled by created my wrapper to read the output stream.
I then latch the stream to the process and bingo!
Here’s the wrapper, its getter and the actual code to get the output:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class RuntimeExec {
public StreamWrapper getStreamWrapper(InputStream is, String type){
return new StreamWrapper(is, type);
}
private class StreamWrapper extends Thread {
InputStream is = null;
String type = null;
String message = null;
public String getMessage() {
return message;
}
StreamWrapper(InputStream is, String type) {
this.is = is;
this.type = type;
}
public void run() {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuffer buffer = new StringBuffer();
String line = null;
while ( (line = br.readLine()) != null) {
buffer.append(line);//.append("\n");
}
message = buffer.toString();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
// this is where the action is
public static void main(String[] args) {
Runtime rt = Runtime.getRuntime();
RuntimeExec rte = new RuntimeExec();
StreamWrapper error, output;
try {
Process proc = rt.exec("ping localhost");
error = rte.getStreamWrapper(proc.getErrorStream(), "ERROR");
output = rte.getStreamWrapper(proc.getInputStream(), "OUTPUT");
int exitVal = 0;
error.start();
output.start();
error.join(3000);
output.join(3000);
exitVal = proc.waitFor();
System.out.println("Output: "+output.message+"\nError: "+error.message);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Get our Articles via Email. Enter your email address.




see ProcessBuilder
http://java.sun.com/j2se/1.5.0/docs/api/java/lang/ProcessBuilder.html