In this tutorial we will see about executing Unix command through Java program and printing the output as same as Unix shell command printing. We can achieve by using Process class in Java.
Process class provides the methods for performing
standard input from the given process,
performing standard output to the process,
waiting for the process to complete its task,
checking exit status of the process and
destroying the process (normally its killing the process).
Constructor in Process class:
Process()
Method in Process class:
abstract InputStream getInputStream()
Used to get the standard input stream of sub-process.
abstract OutputStream getOutputStream()
Used to get the standard output stream of the sub-process.
abstract InputStream getErrorStream()
Used to get the standard error stream of the sub-process.
abstract void destroy()
Used to kill the sub-process.
abstract int exitValue()
Returns the exit value for the sub-process.
abstract int waitFor()
Makes current thread to wait, if necessary, until the process represented by this Process object has terminated.
Now lets see about how to execute Unix command using Process class in Java with simple example of listing folder and files from the current Folder. Second output will show you Error Stream result when we try to unzip a file.
import java.io.InputStream;
public class UnixCommandThroughJava {
public static void main (String args[]) {
String unixCommand = "ls -lh";
InputStream in = null;
try {
StringBuilder commandResult = new StringBuilder();
Process p = Runtime.getRuntime().exec(unixCommand, null);
int returnVal = p.waitFor();
if (returnVal == 0){ // no error
in = p.getInputStream();
}else{ // If any error occurred
in = p.getErrorStream();
}
int readInt;
while ((readInt = in.read()) != -1){
commandResult.append((char)readInt);
}
System.out.println("COMMAND : " + unixCommand + "\n\nOUTPUT : \n" + commandResult.toString());
in.close();
} catch (Exception e) {
System.out.println("An exception occured while executing command " + unixCommand);
e.printStackTrace();
}
}
}
OUTPUT:
No comments:
Write comments