Professional Documents
Culture Documents
Anyway if you no choice and you want to execute native commands from JAVA then its 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 "ls" command in Linux which list down all the files and directory in a folder and you want
to do it using JAVA.
In JAVA we have a class called "java.lang.Runtime" which is used to interact with Runtime system has 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.
try {
// Run ls command
Process process = Runtime.getRuntime().exec(cmd);
} catch (Exception e) {
e.printStackTrace(System.err);
}
This is little nice tip which can be very handy in some specific situation but in by and large its not advised by the very
own reason of making JAVA code platform dependence.
as pointed out by Jaroslav sedlacek If not done properly it can easily hang the application. Java and external
process communicate through buffers. If buffer fills up, the external process stops and waits until java empties
the buffer. Java app has to read both output and error streams of the process to prevent this blocking. There
is good util class ProcessBuilder since 1.5 in java or apache commons exec can be used too.
6 comments :