Running external command from Java & I/O operations


The below Java code, can be used to run any external command which may or may not take input from the console via Input redirection. This code has been tested on Unix/Linux only. Minor modifications may be required for other operating systems.

Uses: java Runner {command} {argument(s)} [-input] [input-file]
e.g: java Runner ‘ls -al’
e.g: java Runner java WordCount -input input.txt

 
/**
* @author shekhar
* @date   02/03/2010
* @description from java run any external command
**/
import java.io.*;

public class Runner{

        Runtime runtime;
        Process process;

        Runner(){
                runtime = Runtime.getRuntime();
        }

        /**
        * @param name of the file, input the the command
        **/

        void writeInput(String fileName){

                try{
                        OutputStream outputstream = process.getOutputStream();
                        OutputStreamWriter outputstreamwriter = new OutputStreamWriter(outputstream);
                        BufferedWriter bufferedwriter = new BufferedWriter(outputstreamwriter);
                        BufferedReader br = new BufferedReader(new FileReader(fileName));
                        String s = br.readLine();

                        /** writing the code into output stream of the process **/

                        while (s != null){
                                bufferedwriter.write(s);
                                s = br.readLine();
                        }
                        bufferedwriter.flush();
                        bufferedwriter.close();

                }catch(Exception e){
                        e.printStackTrace();
                }
        }
        /**
        * @param all the argument of command including command name, arguments, input file
        */

        void run( String[] args ){
                String cmd = "";
                String error = "";
                String output = "";
                int exitVal = -1;

                try{
                        /** parsing the arguments **/

                        for(int i=0;i<args.length;i++){
                                if( args[i].equals ( "-input" ) ){
                                        process = runtime.exec( cmd );
                                        writeInput ( args[ ++i ] );     // passing input file name if any needed;
                                }else{
                                        cmd = cmd + " "+ args[i];
                                        if( i == args.length -1 )
                                                process = runtime.exec( cmd );
                                }
                        }

                        process.waitFor();  // waiting the process to be over

                        exitVal = process.exitValue();

                        BufferedReader ebr = new BufferedReader( new InputStreamReader ( process.getErrorStream() ) );
                        String line = null;

                        while ( (line = ebr.readLine()) != null)
                                error += line+'\n';

                        BufferedReader ibr = new BufferedReader(new InputStreamReader ( process.getInputStream() ) );
                        while ( (line = ibr.readLine()) != null)
                                output += line+'\n';

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

                if( error.trim().length() > 0 ){
                        System.out.println("Error :"+error.trim());     // error if any during the excution of command
                }
                if( output.trim().length() > 0 ){
                        System.out.println("Output :"+output.trim());   // output of the excution of the command
                }

                System.out.println("Exit Value: "+exitVal);
        }

        public static void main(String[] args){
                try{
                        Runner runner = new Runner();
                        runner.run(args);
                }catch(Exception e){
                        e.printStackTrace();
                }
        }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: