Tuesday, November 1, 2016

JDK 8: executing command from java

To execute system/external command we need to use Process class. There are 2 ways to get this instance: 
  1. Using static method Runtime.getRuntime()
  2. Using ProcessBuilder
This is the example code to call ping or whois under Debian TestShell.java:
import java.util.Map;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.BufferedReader;
/*
Ref:
http://docs.oracle.com/javase/8/docs/api/java/lang/ProcessBuilder.html
http://www.javatips.net/blog/java-processbuilder-exampl
http://www.mkyong.com/java/how-to-execute-shell-command-from-java/

*/
class TestShell {
  public static void main(String[] args) {
    System.out.println("Creating ProcessBuilder Object");
    //ProcessBuilder pb = new ProcessBuilder("whois", "garasiku.web.id");
    ProcessBuilder pb = new ProcessBuilder("ping", "www.garasiku.web.id", "-c", "4");
    Map<String, String> env = pb.environment();
    System.out.println("size env: "+env.size());
    //Java 8 only, forEach and Lambda
    env.forEach((k,v)->System.out.println("Key : " + k + " Value : " + v));
    try {
      //Process p = Runtime.getRuntime().exec("ping www.garasiku.web.id -c 4");
      Process p = pb.start();
      System.out.println("dump standard output");
      InputStreamReader isr = new InputStreamReader(p.getInputStream());

      BufferedReader br = new BufferedReader(isr);
      String tmp="";
      while ((tmp = br.readLine()) != null) {
        System.out.println(tmp);
      }
      System.out.println("dump standard error");
      isr = new InputStreamReader(p.getInputStream());

      br = new BufferedReader(isr);
      tmp="";
      while ((tmp = br.readLine()) != null) {
        System.out.println(tmp);
      }
      // waitFor() method is used to wait till the process returns the exit value

      try {
        int exitValue = p.waitFor();
        System.out.println("Exit Value is " + exitValue);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    } catch (IOException e) {
      System.out.println(e.toString());
    }  
  }
}

References:

No comments:

Post a Comment