Java examples for Native OS:Process
execute Shell Command And Get Return 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(executeCommandAndGetReturnCode(command)); }//from ww w.ja v a 2s .c om public static int executeCommandAndGetReturnCode(String command) throws Exception { Process proc = createAndExecuteProcess(command); logForProc(proc); return proc.waitFor(); } 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(); } }