Java examples for Native OS:Shell Command
execute Cmd
import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; public class Main{ public static void main(String[] argv) throws Exception{ String cmd = "java2s.com"; System.out.println(executeCmd(cmd)); }/*from w w w.jav a 2 s .c om*/ public static String executeCmd(String cmd[]) { try { StringBuffer sb = new StringBuffer(); for (int i = 0; i < cmd.length; i++) { Process pro = null; pro = Runtime.getRuntime().exec(cmd[i]); // ProcessBuilder pb = new ProcessBuilder(cmd[i]); // pb.redirectErrorStream(true); // pro = pb.start(); BufferedReader br = null; InputStreamReader isr = new InputStreamReader( pro.getInputStream(), "utf-8"); br = new BufferedReader(isr); String line = br.readLine(); while (line != null) { sb.append(line + "\r\n"); line = br.readLine(); } // System.out.println(sb.toString()); try { pro.waitFor(); } catch (InterruptedException e) { e.printStackTrace(); } finally { try { if (br != null) { br.close(); br = null; } if (isr != null) { isr.close(); isr = null; } if (pro != null) { pro.destroy(); pro = null; } } catch (IOException e) { e.printStackTrace(); } } } return sb.toString(); } catch (Exception e) { e.printStackTrace(); } return null; } }