File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes java.lang.Runtime exec() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "java.lang.Runtime exec()" Watch "java.lang.Runtime exec()" New topic

java.lang.Runtime exec()

Sean Casey
Ranch Hand

Joined: Dec 16, 2000
Posts: 625
I understand that the exec() is used to call a command on the operating system. But how do you get the output from that command that you run? This method returns type Process. I looked in the Process Class, but I wasn't sure how to get the information back, it won't do it automatically will it?
I want to do something simple from a unix shell. I want to create a program that calls the date command, will the output of the date be printed, or do I have to access some underlying stream of class Process to get it? Thanks for your help.
Sean Casey
Ranch Hand

Joined: Dec 16, 2000
Posts: 625
Okay, I found some help on the internet. If anyone else is interested here's the article I found:
Running External Commands in Java Applications
Fahd Shariff
Ranch Hand

Joined: Nov 22, 2002
Posts: 38
I have done this many times:
public void command(String cmd)
Process proc = Runtime.getRuntime().exec(cmd);
displayOutput(proc, proc.getInputStream());
//or you might need
//displayOutput(proc, proc.getErrorStream());
//as the case may be
public void displayOutput(Process proc, InputStream istr) throws IOException

// put a buffered reader input stream on it
BufferedReader br = new BufferedReader(new InputStreamReader(istr));

// read output lines from command
String str;
while ((str = br.readLine()) != null)
//do whatever you want with the strings
System.out.println(str) ;

// wait for command to terminate
try {
catch (InterruptedException e) {
System.err.println("process was interrupted");

// check its exit value
if (proc.exitValue() == 0)

// close stream

This is a standard thing that i use all the time. It should work unless i have made some cut n paste errors

Fahd Shariff<br />"Let the code do the talking"
I agree. Here's the link:
subject: java.lang.Runtime exec()
jQuery in Action, 3rd edition