วันพุธที่ 6 กรกฎาคม พ.ศ. 2554

Code วิธีการรัน คำสั่ง shell ด้วย java.


Code วิธีการรัน คำสั่ง shell ด้วย java.
============================================
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;

public class ExecuteSH {
      public static void main(String args[]) {

            String path = "./";
            String fileShell = "executeable.sh";
            String cmd ="sh "+path + fileShell;
            File inputFile = null;
            try {
                  inputFile = new File(path + fileShell);
                  if (!inputFile.exists()) {
                        throw new FileNotFoundException("input file not found: " + inputFile.getPath());
                  } else {
                        System.out.println("Input Path :: " + inputFile.getPath());
                        System.out.println("shell command :: " + cmd);
                        System.out.println(MNPExecuteSH.executeSH(cmd));
                  }

            } catch (FileNotFoundException fe) {
                  System.out.println("xx error 1:: >> ");
                  fe.printStackTrace();
            } catch (Exception e) {
                  System.out.println("xx error 2:: >> ");
                  e.printStackTrace();

            } finally {
                  System.out.println("Run Done...");
            }

      }

      public static String executeSH(String cmd) {
            System.out.println("Command=" + cmd);
            try {
                  Runtime run = Runtime.getRuntime();
                  Process pr = run.exec(cmd);
                  //System.out.println("Obj Process "+pr);
                  pr.waitFor();
                  //System.out.println("pr.getInputStream() "+pr.getInputStream());
                  BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));
                  String line = "";
                  while ((line = buf.readLine()) != null) {
                        System.out.println(line);
                  }
                  //System.out.println("Test executeSH");
            } catch (Exception e) {
                  // return e.toString();
                  System.out.println(e.toString());
            }
            return "Success";
      }
}