package common; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; /*** * create by zipon 2018-09-10 */ public class ExecCmdUtils { /*** * 根据系统执行命令,只需要传入命令,返回所有命令返回的信息 * @param cmd * @return * @throws IOException */ public static String execCmd(String cmd) throws IOException { String os = System.getProperty("os.name"); String[] preparecmd = {}; if(os!=null && os.toLowerCase().indexOf("windows")>=0) { preparecmd = new String[]{"cmd", "/C", cmd}; }else if (os!=null && os.toLowerCase().indexOf("linux")>=0){ preparecmd = new String[]{"/bin/sh", "-c", cmd}; }else { return null; } Runtime rt = Runtime.getRuntime(); Process p = rt.exec(preparecmd); //取得命令结果的输出流 InputStream fis=p.getInputStream(); //用一个读输出流类去读 InputStreamReader isr=new InputStreamReader(fis,"GBK"); //用缓冲器读行 BufferedReader br=new BufferedReader(isr); String line=null; String result = ""; //直到读完为止 while((line=br.readLine())!=null) { result = result+line+" "; } //去掉最后一个换行符 result = result.substring(0,result.length()-2); System.out.println("执行结果: "+result); return result; } }