Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. package sample;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.File;
  5. import java.io.IOException;
  6. import java.io.InputStreamReader;
  7. import java.util.Map;
  8.  
  9.  
  10. /**
  11.  * Simple usage example for class java.lang.ProcessBuilder under Windows (XP, Vista, ...)
  12.  */
  13. public class ProcessBuilderTest {
  14.     /**
  15.      * @param args no arguments needed
  16.      */
  17.     public static void main(String[] args) {
  18.         ProcessBuilder pb = new ProcessBuilder();
  19.         pb.redirectErrorStream(true);
  20.         pb.directory(new File("C:/"));
  21.         pb.command("cmd", "/c", "dir");
  22.         //Map<String, String> env = pb.environment();
  23.         //env.put("PB_SAMPLE_VAR", "Hello World!");
  24.         //pb.command("cmd", "/c", "echo", "%PB_SAMPLE_VAR%");
  25.        
  26.         Process p;
  27.         try {
  28.             p = pb.start();
  29.         }
  30.         catch (Exception e) {
  31.             e.printStackTrace();
  32.             System.exit(1);
  33.             return;
  34.         }
  35.        
  36.         System.out.println("stdout/stderr of command: " + pb.command());
  37.         System.out.println("-------------------------");
  38.         InputStreamReader isr = null;
  39.         BufferedReader    br  = null;
  40.         try {
  41.             isr = new InputStreamReader(p.getInputStream());
  42.             br  = new BufferedReader(isr);
  43.        
  44.             String line;
  45.             for (;;) {
  46.                 try {
  47.                     line = br.readLine();
  48.                     if (line == null) {
  49.                         break;
  50.                     }
  51.                     System.out.println(line);
  52.                 }
  53.                 catch (IOException e) {
  54.                     e.printStackTrace();
  55.                     break;
  56.                 }
  57.             }
  58.         }
  59.         finally {
  60.             if (br != null) {
  61.                 try { br.close(); } catch (Exception ex) { /* */ }
  62.             }
  63.         }
  64.        
  65.         int exitcode = -1;
  66.         try {
  67.             exitcode = p.waitFor();
  68.         } catch (InterruptedException e) {
  69.             e.printStackTrace();
  70.             exitcode = -42;
  71.         }
  72.         System.out.println("-------");
  73.         System.out.println("exitcode: " + exitcode);
  74.     }
  75. }