It is supposed to be printing the list of files (in file1) and the current process (in file2). However, it only prints in the console(Terminal) what is in file1. I checked what is in file2, and it has content as expected, but it does not print in the console(Terminal) what is in file2. Also, another.hasNext() is always false. Can any body help me fix this? Here is my code:
File file1 = new File("1.txt");
ProcessBuilder pb1 = new ProcessBuilder("ls");
pb1.redirectOutput(file1);
pb1.start();
Scanner s = new Scanner(file1);
while(s.hasNext()) {
System.out.println(s.next());
}
System.out.println("_____________________________");
File file2 = new File("2.txt");
pb1 = new ProcessBuilder("ls");
pb1.redirectOutput(file2);
pb1.start();
Scanner another = new Scanner(file2);
while(another.hasNext()) {
System.out.println(another.next());
}
ProcessBuilder will start a new process to run the command(ls), it's asynchronous.
You can use waitFor
to wait the process finish executing:
pb1.redirectOutput(file1);
pb1.start().waitFor();
...
pb1.redirectOutput(file2);
pb1.start().waitFor();