How to Execute Native Shell commands from Java Program? Example (original) (raw)

How to execute native shell commands from JAVA
Though it’s not recommended some time it’s become necessary to execute a native operating system or shell command from Java, especially if you are doing some kind of reporting or monitoring stuff and required information can easily be found using the native command. This is not advised though because then you will lose platform independence which is why we mostly used Java. Anyway, if you have no choice and you want to execute native commands from Java then it's good to know that how we can do it, many of you probably know this but for those who don't know and have never done it, we will see through an example.

Suppose you want to execute the "ls" command in Linux which lists down all the files and directories in a folder and you want to do it using Java.

There are two main approaches for executing shell commands in Java either by using Runtime.exec() method or ProcessBuilder, which was added in Java 1.5.

Here is a simple example using the ProcessBuilder API in Java as shown below

How to Execute Native Shell commands from Java Program? Example

In Java we have a class called "java.lang.Runtime" which is used to interact with the Runtime system has the facility to execute any shell command using method exec().

Here is the code sample which can be used to execute any native command from Java.

final String cmd = "ls -lrt";

int pid = -1;

try {

Process process = Runtime.getRuntime().exec(cmd);

} catch (Exception e) { e.printStackTrace(System.err); }

This is a little nice tip that can be very handy in some specific situations but by and large it's not advised by the very own reason of making JAVA code platform dependent.

As pointed out by Jaroslav sedlacek If not done properly it can easily hang the application. Java and external process communicate through buffers. If the buffer fills up, the external process stops and waits until java empties the buffer.

How to execute native shell commands from Java Program? Example

Java app has to read both output and error streams of the process to prevent this blocking.

There is also a good util class ProcessBuilder since 1.5 in Java or Apache commons exec can be used too.