I am writing a program to read commands from a file, execute them and print the result of each command.
This is what i have: import java.io.*;
public class StatsGenerator {
public static void main(String [] args) throws IOException {
ProcessBuilder builder = new ProcessBuilder( "/bin/bash" );
Process p = builder.start();
// get output from the process
InputStream is = p.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader processOutput = new BufferedReader(isr);
InputStream errorStream = p.getErrorStream();
InputStreamReader inputStreamReader = new InputStreamReader(errorStream);
BufferedReader processErrorOutput = new BufferedReader(inputStreamReader);
// get input to the process
BufferedWriter processInput = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
// get commands to execute
File f = new File("commands.txt");
FileReader fileReader = new FileReader(f);
BufferedReader commandsReader = new BufferedReader(fileReader);
String command, output;
while((command = commandsReader.readLine()) != null) {
System.out.printf("Output of running %s is:\n", command);
processInput.write(command);
processInput.newLine();
processInput.flush();
while (processErrorOutput.ready() && (output = processErrorOutput.readLine()) != null) {
System.out.println(output);
}
while ((output = processOutput.readLine()) != null) {
System.out.println(output);
}
}
// close process
processInput.write("exit");
processInput.newLine();
processInput.flush();
// close streams
commandsReader.close();
processErrorOutput.close();
processInput.close();
processOutput.close();
}
}
commands.txt
java Solve problems/problem01.txt
java Solve problems/problem02.txt
java Solve problems/problem03.txt
However this runs and outputs the result of the first command but gets stuck on the second one ... ( and I know that Solve can solve the second one )
What am i doing wrong ?
EDIT1:
Turns out the "Exception in thread 'main'" error from the picture is due to me pressing the CMD+C. This still does not explain why it stops outputting.