execute Shell Command And Get Output - Java Native OS

Java examples for Native OS:Process

Description

execute Shell Command And Get Output

Demo Code


import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class Main{
    public static void main(String[] argv) throws Exception{
        String command = "java2s.com";
        System.out.println(executeCommandAndGetOutput(command));
    }//from www . j av  a2s .c  o  m
    public static String executeCommandAndGetOutput(String command)
            throws Exception {
        Process proc = createAndExecuteProcess(command);
        logForProc(proc);
        return getOuputMessageOfCommand(proc.getInputStream());
    }
    private static Process createAndExecuteProcess(String command)
            throws IOException {
        String system = System.getProperty("os.name").toLowerCase();
        if ("unix".equals(system) || "mac os x".equals(system)
                || "linux".equals(system)) {
            return Runtime.getRuntime().exec(
                    new String[] { "/bin/sh", "-c", command });
        } else if ("windows".equals(system)) {
            return Runtime.getRuntime().exec(
                    new String[] { "cmd.exe", "/c", command });
        } else {
            throw new RuntimeException("Unknown OS [" + system + "]");
        }
    }
    public static void logForProc(Process proc) {
        // any error message?
        StreamGobbler errorGobbler = new StreamGobbler(
                proc.getErrorStream(), "ERROR");

        // any output?
        StreamGobbler outputGobbler = new StreamGobbler(
                proc.getInputStream(), "OUTPUT");

        // kick them off
        errorGobbler.start();
        outputGobbler.start();
    }
    public static String getOuputMessageOfCommand(InputStream is) {
        String message = "";
        try {
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(">>" + line);
                message += line;
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
        return message;
    }
}

Related Tutorials