Warning: Use of undefined constant fixed - assumed 'fixed' (this will throw an Error in a future version of PHP) in /home/webtro13/domains/farenda.com/public_html/wp-content/themes/moments/header.php on line 65
class="header_container_flat">

Problem:

How to run external process in Java? In this post we’re going to show how to use ProcessBuilder to work with external processes using new API from Java 7.

The java.lang.ProcessBuilder class allows to start external processes and is available since… forever, but in Java 7 it has been extended with the new ProcessBuilder.Redirect class that specializes in redirection ofinput, output, and errorstreams.

Solution:

In the following example we’re going to start two processes. Both will have error stream redirected to /tmp/process.log. Note that we are using Redirect.appendTo(File), because we want to append to the log instead of rewriting it each time a process starts.

The first process will use cat command to get information about RAM from /proc/meminfo file that is available on Linux machines. We will show how to read its output and display it. The process will end up cleanly.

The second process will run ls to display content of /root directory, to which we don’t have access, so the process will output error message to the log file.

The code is straightforward. We are using method destroyForcibly() (added in Java 8) to kill the process, to be able to obtain exit code from the process. Else it could throw an exception that the process hasn’t finished yet.