• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

java.lang.Runtime exec()

 
Sean Casey
Ranch Hand
Posts: 625
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
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
Posts: 625
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 38
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 {
proc.waitFor();
}
catch (InterruptedException e) {
System.err.println("process was interrupted");
}

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

// close stream
br.close();
}

This is a standard thing that i use all the time. It should work unless i have made some cut n paste errors
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic