Run a command from a Java application dealing properly with stdin, stdout and stderr

If you want to run an external command from a Java application you have to deal properly with the input, output and error file descriptors or it won’t work. The key is to read the output and error buffers. This is a simple example on how to do this:

import java.io.*;

public class CmdExec {

  public static void main(String argv[]) {
    try {
      String line;
      OutputStream stdin = null;
      InputStream stderr = null;
      InputStream stdout = null;

      // launch the command and grab stdin/stdout and stderr
      Process process = Runtime.getRuntime().exec("ls -la");
      stdin = process.getOutputStream();
      stderr = process.getErrorStream();
      stdout = process.getInputStream();

      // You could write to sdtin too but it's useless for the ls we are doing ;)
      line = "param1" + "n";   
      stdin.write(line.getBytes() );
      stdin.flush();

      line = "param2" + "n";
      stdin.write(line.getBytes() );
      stdin.flush();

      stdin.close();
      
      // clean up if any output in stdout
      BufferedReader brCleanUp = new BufferedReader(new InputStreamReader(stdout));
      while ((line = brCleanUp.readLine()) != null) {
        System.out.println ("[Stdout] " + line);
      }
      brCleanUp.close();
      
      // clean up if any output in stderr
      brCleanUp = 
        new BufferedReader (new InputStreamReader (stderr));
      while ((line = brCleanUp.readLine ()) != null) {
        //System.out.println ("[Stderr] " + line);
      }
      brCleanUp.close();

      System.out.println("Exit value: " + process.exitValue());

      process.destroy();
    } catch (Exception err) {
      err.printStackTrace();
    }
  }
}

You might also like

Select different available java and javac versions in Ubuntu with update-alternatives
It's possible to have more than one version of Java in the same machine.If you have more than...

Select different available java and javac versions in Ubuntu with update-alternatives
It's possible to have more than one version of Java in the same machine.If you have more than...

Type the full pathname of a JDK installation when running Oracle SQL Developer
When you execute the Oracle SQL Developer for the firts time it'll asks you to give the full pathname...

Fix “Communications link failure” in Java applications with MySQL
You may have problems connecting to MySQL from Java applications using Connector/J (the Java connector...

  1. Thx,this is very helpful. But there is a problerm, u didn’t terminate the process after the cmdline execution. If I have a program which cyclically invoke this part as a sub method, there will be too much resource consumption.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.