7. Runtime (System Level Process) using groovy

System level process means create program that interact to system level to process code written in program. In UNIX, we usually do system level process through terminal meanwhile, on windows system we usually use command prompt (cmd). All the process on system level can actually be done by using program. In java we usually call it with runtime process. There are several steps to do it in java. First, we need to import java.io then, inside of try and catch block, we need to use instance of Process object to execute the command. And for the output, we can use BufferedReader as the temporary container. Here is the example :

class RuntimeProcess{
    public static void main(String [] args){
        String command = "help";
        Process p = null;
        try{
            p = Runtime.getRuntime().exec(command);
            BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String result = "";
            while((result = br.readLine()) != null){
                System.out.println(result);
            }
        }catch(Exception e){
            System.out.println("error "+e);
        }
        finally{
            if(p!=null){
                p.destroy();
            }
        }
    }
}


As we know that the process above there quite complicated and need a long way to code. On the other hand, groovy has GDK as the extension of JDK or it’s called Groovy JDK. We can do runtime in quite simple on line code and see the output directly there. By using [COMMAND].execute here is the code.

So, which one do you choose long and complicated or the simple and sweet one. 

Tagged: , , , , ,

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

%d bloggers like this: