Monday, November 4, 2019

How to execute command from Java in Windows



public static void main(String[] args) {
  
  String command = "";
  Process process  = Runtime.getRuntime().exec(command);

  // thread waiting for error
  StreamGobbler errorGobbler = new StreamGobbler(process.getErrorStream(), "ERROR");

  // thread waiting for output
  StreamGobbler outputGobbler = new StreamGobbler(process.getInputStream(), "OUTPUT");

  errorGobbler.start();
  outputGobbler.start();

  // wait for process to finish
  p.waitFor();
  p.destroy();
}

 class StreamGobbler extends Thread {

   InputStream is;
   String type;
   StringBuffer buffer = new StringBuffer();

   StreamGobbler(InputStream is, String type) {
     this.is = is;
     this.type = type;
   }

   public void run() {
     InputStreamReader isr = null;
     BufferedReader br = null;
     try {

       isr = new InputStreamReader(is);
       br = new BufferedReader(isr);
       String line = null;
       while ((line = br.readLine()) != null) {
         if (buffer != null) {
           buffer.append(line).append("\n");
         }
         System.out.println(type + ">" + line);
       }
     } catch (IOException ioe) {
       e.printStackTrace();
     } finally {
       try {
         br.close();
         isr.close();
       } catch (IOException e) {
         e.printStackTrace();
       }
     }
  }


Done!!

1 comment:

LinkWithin

Related Posts Plugin for WordPress, Blogger...