ProcessBuilder
. For instance, the example below shows how we can execute the diff
command.
ProcessBuilder builder = new ProcessBuilder("diff", "-u", FIRST_FILE, SECOND_FILE);
Process p = builder.start();
p.waitFor();
Both of Process
class and Process
class provide methods to redirect outputs and error message of the underlying process that they represent. In our case, we will use the getInputStream()
and getErrorSream()
mtehods from the Process class. Note that the getInputStream()
is the output stream of the subprocess. It is called input stream because from the point of the client of the Process
object, the output of the subprocess is its input.
BufferedReader readerOfOutput = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = readerOfOutput.readLine()) != null) {
System.out.println(line);
}
BufferedReader readerOfError = new BufferedReader((new InputStreamReader(p.getErrorStream())));
while ((line = readerOfError.readLine()) != null) {
System.out.println(line);
}
----- END -----
©2019 - 2024 all rights reserved