Tuesday, 7 June 2016

How call shell from Java?

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class ExecuteShellComand {

 public static void main(String[] args) {

  ExecuteShellComand obj = new ExecuteShellComand();

  String domainName = "google.com";
  
  //in mac oxs
  String command = "ping -c 3 " + domainName;
  
  //in windows
  //String command = "ping -n 3 " + domainName;
  
  String output = obj.executeCommand(command);

  System.out.println(output);

 }

 private String executeCommand(String command) {

  StringBuffer output = new StringBuffer();

  Process p;
  try {
   p = Runtime.getRuntime().exec(command);
   p.waitFor();
   BufferedReader reader = 
                            new BufferedReader(new InputStreamReader(p.getInputStream()));

                        String line = "";   
   while ((line = reader.readLine())!= null) {
    output.append(line + "\n");
   }

  } catch (Exception e) {
   e.printStackTrace();
  }

  return output.toString();

 }
PING google.com (74.125.135.x): 56 data bytes
RESULT:
64 bytes from 74.125.135.x: icmp_seq=0 ttl=53 time=8.289 ms
64 bytes from 74.125.135.x: icmp_seq=1 ttl=53 time=7.733 ms
64 bytes from 74.125.135.x: icmp_seq=2 ttl=53 time=8.343 ms

--- google.com ping statistics ---
3 packets transmitted, 3 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 7.733/8.122/8.343/0.276 ms
null

No comments:

Post a Comment