Friday, 14 July 2017

Call shell script from Java code

Below is the code to call the shell script from Java code. This will call the shell script and wait for it's execution and print the output.

public static void main(String[] args) throws Exception {
        try {
                String param1=args[0];
               
                String scriptName = "/root/script.ksh";
                String commands[] = new String[]{scriptName,param1};

                Runtime rt = Runtime.getRuntime();
                Process proc = rt.exec(commands);
                proc.waitFor();
                StringBuffer output = new StringBuffer();
                BufferedReader reader = new BufferedReader(new       InputStreamReader(proc.getInputStream()));
                String line = "";                      
                while ((line = reader.readLine())!= null) {
                        output.append(line + "\n");
                }
                System.out.println("===> " + output);
        } catch (Exception e) {
                e.printStackTrace();
        }

No comments:

Post a Comment

Thank You for your valuable comment

Difference between class level and object locking and static object lock

1) Class level locking will lock entire class, so no other thread can access any of other synchronized blocks. 2) Object locking will lo...