I'm trying to get my head around the ProcessBuilder class, so I built this test class. Needless to say, it doesn't work, but I can't figure out why. Here's the code:
import java.io.*; /*Test Class*/ public class TestMe { public static void main(String[] args) { ProcessBuilder pb = null; Process shell = null; BufferedReader fromProcess = null; BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); PrintWriter toProcess = null; String command = ""; String line = ""; try { System.out.printf("-------------\n"); System.out.printf("Testing Process Builder%n"); pb = new ProcessBuilder ("/bin/bash"); System.out.printf("Merge stdout with stderr? %b%n", pb.redirectErrorStream()); if (pb.redirectErrorStream() != true) { System.out.printf("\tMerging both streams%n"); pb.redirectErrorStream(true); System.out.printf("\tIt is now %b%n", pb.redirectErrorStream()); } System.out.printf("Creating Shell process\n"); shell = pb.start(); System.out.printf("Getting stdout\n"); fromProcess = new BufferedReader (new InputStreamReader (shell.getInputStream())); System.out.printf("Getting stdin\n"); toProcess = new PrintWriter (shell.getOutputStream(), true); System.out.printf("Time to pass a command!%n"); System.out.printf("\tstdin :- "); command = input.readLine(); System.out.printf("\tCommand is: %s%n", command); System.out.printf("Handing command over to process...%n"); toProcess.print(command); System.out.printf("Getting output...%n"); do { line = fromProcess.readLine(); System.out.printf("\t%s%n",line); } while (line != null); //Close I/O toProcess.close(); fromProcess.flush(); fromProcess.close(); System.printf("It Worked!%n"); } catch (Exception e) { System.out.printf("%nError: %s%n", e.getMessage()); e.printStackTrace(); } } //End main method } //End class TestMe
In my head, I should be able to pass a command (say, "ls") and get the output of the command printed out to the screen. Where am I going wrong? Any help would be greatly appreciated.
Zo...