// We use this to start commands
ProcessBuilder launcher = new ProcessBuilder();
// Our inherited environment vars. We may modify these below
Map<String,String> environment = launcher.environment();
// Our processes will merge error stream with standard output stream
launcher.redirectErrorStream(true);
// Where we read the user's input from
BufferedReader console =
new BufferedReader(new InputStreamReader(System.in));
while(true) {
try {
System.out.print("> "); // display prompt
System.out.flush(); // force it to show
String command = console.readLine(); // Read input
if (command.equals("exit")) return; // Exit command
else if (command.startsWith("cd ")) { // change directory
launcher.directory(new File(command.substring(3)));
}
else if (command.startsWith("set ")) {// set environment var
command = command.substring(4);
int pos = command.indexOf('=");
String name = command.substring(0,pos).trim();
String var = command.substring(pos+1).trim();
environment.put(name, var);
}
else { // Otherwise it is a process to launch
// Break command into individual tokens
String[] words = command.split(" ");
launcher.command(words); // Set the command
Process p = launcher.start(); // And launch a new process
// Now read and display output from the process
// until there is no more output to read
BufferedReader output = new BufferedReader(
new InputStreamReader(p.getInputStream()));
String line;
while((line = output.readLine()) != null)
System.out.println(line);
// The process should be done now, but wait to be sure.
p.waitFor();
}
}
catch(Exception e) {
System.out.println(e);
}
}