Here you can find the source of executeCommand(final ProcessBuilder pb)
public static String executeCommand(final ProcessBuilder pb)
//package com.java2s; import java.io.BufferedReader; import java.io.InputStreamReader; public class Main { public static String executeCommand(final ProcessBuilder pb) { final StringBuffer output = new StringBuffer(); Process p;/*from ww w. java 2 s . c om*/ try { // System.out.println("Before start"); p = pb.start(); // System.out.println("after start"); // p.waitFor(); // not work for dir, not work sometimes for all // commands, never comes back // System.out.println("after waitFor"); final BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); /* String line = reader.readLine(); while (line != null && line.length() > 0) { output.append(line + "\n"); line = reader.readLine(); } */ String line = ""; // System.out.println("Before read while"); while ((line = reader.readLine()) != null) { output.append(line + "\n"); // System.out.println("inside reade while"); if (!reader.ready()) { // System.out.println("inside not ready"); Thread.sleep(3000); if (!reader.ready()) { // System.out.println("not ready break"); break; } /* if (p.exitValue() == 0) { System.out.println("ready break"); break; } else { // reader.wait(3000); if (!reader.ready()) { System.out.println("not ready break"); break; } }*/ } } final int i = p.exitValue(); System.out.println("Retrun code: " + i); // if (i != 0) // throw new Exception("failed to call the CMD."); } catch (final Exception e) { e.printStackTrace(); } System.out.println(output.toString()); return output.toString(); } public static String executeCommand(final Runtime r, final String command) { final StringBuffer output = new StringBuffer(); Process p; try { System.out.println(command); p = r.exec("cmd /C " + command); // p.waitFor();//not work for dir final BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = reader.readLine(); while (line != null && line.length() > 0) { output.append(line + "\n"); line = reader.readLine(); } /* final BufferedReader readerErr = new BufferedReader( new InputStreamReader(p.getErrorStream())); if (readerErr == null) { String lineErr = ""; while ((lineErr = readerErr.readLine()) != null) { output.append(lineErr + "\n"); } } */ } catch (final Exception e) { e.printStackTrace(); } return output.toString(); } }