Menggaulimu's Blog

Apa Aja Deh, Suka-Suka Gw

Execute Shell Command From Java

Code Example :

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

public class ExecShell {

   public static void main(String[] args) {

      String cmd = "ls -al";
      Runtime run = Runtime.getRuntime();
      Process pr = null;
      try {
         pr = run.exec(cmd);
         pr.waitFor();
         BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));
         String line = "";
         while ((line=buf.readLine())!=null) {
            System.out.println(line);
         }
      } catch (IOException e) {
         e.printStackTrace();
      } catch (InterruptedException e) {
         e.printStackTrace();
      }
   }

}

Leave a comment