Tuesday, May 29, 2012

How to execute commands in Java?

Lets see some Java Code For Executing A Command usually executed on a shell or a command line



Okay? "Why will I ever run a command in java?" you ask?

It so happens that you will end up having to connect to a remote machine and execute some command there and checking its output.

Also, sometimes it is far easier to use the inbuilt commands to do hardcore text processing.

Now onto the code. In this example we will run the jar command to display the contents of the jar-file jmockit.jar.

public class JARDisplay {

 public static void main(String[] args) throws IOException {

  //the jar whose contents we want to display
  String PATH_TO_JAR_FILE = "C:\\jmockit.jar"; 
  
  //Execute the command, jar tvf C:\jmockit.jar
  Process p = Runtime.getRuntime().exec("jar tvf " + PATH_TO_JAR_FILE);

  // read the command output from the process's input stream. 
  BufferedReader commandOutputReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
  String op = null;

  //Display the output of the command line by line
  while ((op = commandOutputReader.readLine()) != null) {
   System.out.println(op);

  }
 }
}

The following is  the output when I run the above program in eclipse: 


But what happens if I goof up the command and give a wrong file name?
say jmit.jar ?

 On the prompt, this is what it shows


Then the above program would run and display nothing on the  java console. How would we get the same output as we got in the image above?

Just as we read the InputStream for the returned Process, we need to read the ErrorStream . Look at the code below to understand the changes.


public class JARDisplay {

 public static void main(String[] args) throws IOException {
  //the jar whose contents we want to display
  String PATH_TO_JAR_FILE = "C:\\jmit.jar"; 
  
  //Execute the command, jar tvf C:\jmockit.jar
  Process p = Runtime.getRuntime().exec("jar tvf " + PATH_TO_JAR_FILE);

  // read the command output from the process's input stream. 
  BufferedReader commandOutputReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
  String op = null;
  //Display the output of the command line by line
  
  while ((op = commandOutputReader.readLine()) != null) {
   System.out.println(op);
  }
  //Check the Error Stream for errors
  BufferedReader stdError = new BufferedReader(new InputStreamReader(
    p.getErrorStream()));

  // read any errors from the attempted command
  while ((op= stdError.readLine()) != null)
   System.out.println(op);
  
 }

}

And now for the output on the eclipse java console..



Its the same error text what we got on the prompt..

Thats it for now! Hope you enjoyed the tutorial.

Please leave comments. Your words will encourage me to write more of these...

No comments:

Post a Comment