My linux world » Java – Process

Java - Process


In some case, we want to run some external commands.
Here i will show you how to do it.

For example we want to run the command: ls -la

Contents

Set the command we want to run

// Set the command to run
String command="ls -la";

Start ProcessBuilder

// Initialize process builder.
ProcessBuilder processBuilder = new ProcessBuilder( command );
 
// And start it
Process process = processBuilder.start();

Set StdOut and StdErr

// Redirect StdOut to LOGGER with info level
final StreamPumper stdOutPumper = new StreamPumper( process.getInputStream(), LOGGER::info);
stdOutPumper.start();
 
// Redirect StdErr to LOGGER with error level
final StreamPumper stdErrPumper = new StreamPumper( process.getErrorStream(), LOGGER::error);
stdErrPumper.start();

Run process

You can exec process :

// Exec process and get exit code.
int exitCode = process.waitFor();

You can fork process :

// Fork process and get exit code.
int exitCode = process.wait();

Now do something with exitCode

if(exitCode != 0) {
  LOGGER.debug("Process exit with code != O");
}

Copyright © 2024 My linux world - by Marc RABAHI
Design by Marc RABAHI and encelades.