简单的静态函数
SysCmd.java:
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class SysCmd { public static String autoExec(String cmdLine) throws IOException, InterruptedException { if (System.getProperty("os.name").matches(".*[Ww]indows.*")) { return exec(new String[] { "cmd", "/c", cmdLine }); } else { return exec(new String[] { "sh", "-c", cmdLine }); } } public static String exec(String[] cmdArray) throws IOException, InterruptedException { Process p = Runtime.getRuntime().exec(cmdArray); String line = null; StringBuffer result = new StringBuffer(); BufferedReader brIn = new BufferedReader(new InputStreamReader(p.getInputStream())); while ((line = brIn.readLine()) != null) { result.append(line + "\n"); } brIn.close(); BufferedReader brErr = new BufferedReader(new InputStreamReader(p.getErrorStream())); while ((line = brErr.readLine()) != null) { result.append(line + "\n"); } brErr.close(); return result.toString(); } }