// File:  Execute.java - show how to execute operating system commands

// The single argument form executes any simple command
// The array form allows you to utilize I/O redirection

import java.io.*;

public class Execute {

    Execute(String sCmd, String[] sArray) throws IOException, InterruptedException {
        System.out.println("Command to be executed:  " + sCmd);

        // Execute the command
        Process pro;
        if (sArray == null)
            pro = Runtime.getRuntime().exec(sCmd);
        else
            pro = Runtime.getRuntime().exec(sArray);

        // Wait until it has completed execution
        pro.waitFor();

        // What did the process output from the Input pipe
        // back to this process?
        InputStream out = pro.getInputStream();

        // Output it (really slowly) (only if bytes are available)
        if (out.available() > 0) {
            int i;
            while ((i = out.read()) != -1)
                System.out.print((char) i);
        }

        // Just a little separation...
        System.out.println();
        System.out.println("----------");
        System.out.println();
    }

    public static void main(String[] args) throws IOException, InterruptedException {
        System.out.println("Execute Operating System Commands");
        System.out.println();
        new Execute("date", null);
        new Execute("ping www.chevron.com", null);
        new Execute("telnet fog.ccsf.org", null);
        System.out.println("\nCreate a file named 'data.txt' containing several lines of text\n");
        new Execute("NotePad", null);

        // These two commands are set up for Windows XP/NT
        // You easily could substitute other shells, like /bin/sh, for UNIX
        // Format:  
        //   <shell> <shell options> <command line, including pipes & redirection>
        String[] sCmd1 = { "C:\\WINDOWS\\system32\\cmd.exe", "/c", "sort", 
                                                    "<", "data.txt",
                                                    ">", "out1.txt" };
        new Execute("*", sCmd1);

        String[] sCmd2 = { "C:\\WINDOWS\\system32\\cmd.exe", "/c", "head", "-7", 
                                                    "<", "out1.txt", "|",
                                                    "deroff", "-w", "|",
                                                    "sort",   
                                                    ">", "out2.txt" };
        new Execute("*", sCmd2);

        System.out.println("*** FINI ***");
        System.out.println();
    }

}

/*
    The general format:  Process p = Runtime.getRuntime().exec(command);

    In UNIX/Linux, to execute a built-in command you need to specify the shell:

    String[] cmdargs = { "/bin/sh", "-c", "sort file | uniq" };
    Process p = Runtime.getRuntime().exec(cmdargs);
*/
