I have seen dozens of examples of launching a Program from Java, but none of these address the following
- Launch a process.
- Wait for it to complete.
- Get the standard output.
- Get the standard error.
Most examples just show you how to call process.exec() and that’s it.So this code attempts to achieve all of the above.
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* @author $Author$
* @version $Revision$
*/
public class TestProcess
{
public static void main(String[] args)
{
try
{
Process process = Runtime.getRuntime().exec(args,null,new File(System.getProperty("user.dir")));
process.waitFor();
BufferedReader inputStreamReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
BufferedReader errStreamReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
StringBuffer output = new StringBuffer();
StringBuffer error = new StringBuffer();
for(String line;(line=inputStreamReader.readLine())!=null;)
{
output.append(line);
}
for(String line;(line=errStreamReader.readLine())!=null;)
{
error.append(line);
}
System.out.println("output = " + output);
System.out.println("error = " + error);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}





Not sure if your program will behave properly or not. You are reading the output first and once output is finished, reading the error. You may come across issues in case the output it too large.
Solution:
You could read the output and error in separate threads and wait for the process to exit in the main thread itself.
I tried this and it works very well.
Yes Nitin, you are quite right.
Reading the output, if it is large, in a new thread could be beneficial under some circumstances.
But in most cases, my guess is, you may not really require it as
1.Your output may not be large.
2.Even if your output is large, you may specifically require a synchronous approach to reading the stdout and stderr,rather than spawning a seprate thread to read the output.
Just for the groove, here’s the above code in Groovy:
def myFilesProcess = “cmd /c dir”.execute(null, new File(System.getProperty(“user.dir”)))
println “Files: ${myFilesProcess.text}”
println “Errors: ${myFilesProcess.errorStream.text}”
Who gives a shit about groovy. He posts a good tut in java and you throw this shit out. Thanks for the info Neel.