陳鍾誠的程式作品集 -- 執行命令列程式 (Runtime)
程式作品C 語言JavaC#JavaScript常用函數文字處理遊戲程式衛星定位系統程式資料結構網路程式自然語言人工智慧機率統計資訊安全等待完成訊息相關網站參考文獻最新修改簡體版English |
範例:命令列指令呼叫import java.util.*; import java.io.*; public class TestExec { public static void main(String args[]) { try { Runtime rt = Runtime.getRuntime(); // Process proc = rt.exec("javac"); // Process proc = rt.exec("javac"); Process proc = rt.exec("start http://www.google.com/"); InputStream stderr = proc.getErrorStream(); InputStreamReader isr = new InputStreamReader(stderr); BufferedReader br = new BufferedReader(isr); String line = null; System.out.println("<ERROR>"); while ( (line = br.readLine()) != null) System.out.println(line); System.out.println("</ERROR>"); int exitVal = proc.waitFor(); System.out.println("Process exitValue: " + exitVal); } catch (Throwable t) { t.printStackTrace(); } } } 範例:命令列指令呼叫 : 將輸出轉到檔案import java.util.*; import java.io.*; public class Runtime1 { public static void main(String args[]) { exec("start http://www.google.com.tw/"); } public static boolean exec(String command) { try { String osName = System.getProperty("os.name" ); String[] cmd = { "cmd.exe", "/C", command } ; if (osName.equals( "Windows 95" )) cmd[0] = "command.exe"; Runtime rt = Runtime.getRuntime(); System.out.println("Execute " + cmd[0] + " " + cmd[1] + " " + cmd[2]); Process proc = rt.exec(cmd); // 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(); // any error??? int exitVal = proc.waitFor(); System.out.println("ExitValue: " + exitVal); return true; } catch (Throwable t) { t.printStackTrace(); return false;} } } class StreamGobbler extends Thread { InputStream is; String type; StreamGobbler(InputStream is, String type) { this.is = is; this.type = type; } public void run() { try { InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line=null; while ( (line = br.readLine()) != null) System.out.println(type + ">" + line); } catch (IOException ioe) { ioe.printStackTrace(); }} } |
page revision: 1, last edited: 04 Nov 2010 05:14
Post preview:
Close preview