java.lang.Runtime.exec(String command, String[] envp) 方法實例
java.lang.Runtime.exec(String command, String[] envp) 方法在指定環境的獨立進程中執行指定的字符串命令。這是一個方便的方法。exec(command, envp) 調用行爲完全相同於調用exec(command, envp, null)。Declaration
以下是java.lang.Runtime.exec()方法的聲明
public Process exec(String command, String[] envp)
參數
- command -- 指定的系統命令。
- envp -- 字符串數組,其中的每個元素都有其格式爲name = value設置環境變量,則返回null,如果子進程應該繼承當前進程的環境。
返回值
該方法返回一個新的Process對象,用於管理子進程
異常
SecurityException -- 如果安全管理器存在,並且其checkExec方法不允許創建子進程
IOException -- 如果發生I/ O錯誤
NullPointerException --如果命令爲空,或者envp的元素之一爲null
IllegalArgumentException -- 如果命令是空的
例子
下面的例子顯示lang.Runtime.exec()方法的使用。
package com.yiibai; import java.io.File; public class RuntimeDemo { public static void main(String[] args) { try { // print a message System.out.println("Executing notepad.exe..."); // create a process and execute notepad.exe and currect environment Process process = Runtime.getRuntime().exec("notepad.exe", null); // print another message System.out.println("Notepad should now open."); } catch (Exception ex) { ex.printStackTrace(); } } }
讓我們來編譯和運行上面的程序,這將產生以下結果:
Executing notepad.exe... Notepad should now open.