java.lang.Runtime.exec(String command, String[] envp, File dir)方法實例
java.lang.Runtime.exec(String command, String[] envp, File dir) 方法在指定環境和工作目錄的獨立進程中執行指定的字符串命令。這是一個方便的方法。exec(command, envp, dir)調用行爲完全相同於調用 exec(cmdarray, envp, dir),其中cmdarray是命令的所有標記的數組。
更確切地說,該命令串被分成使用由調用new StringTokenizer(command) 與字符的類別沒有進一步的修改創建StringTokenizer令牌。由標記生成器生成的令牌,然後以相同的順序放置在新的字符串數組cmdarray。
聲明
以下是**java.lang.Runtime.exec()**方法的聲明
public Process exec(String command, String[] envp, File dir)
參數
command -- 指定的系統命令。
envp -- 字符串數組,其中的每個元素都有其格式爲name = value設置環境變量,則返回null,如果子進程應該繼承當前進程的環境。
dir --子進程的工作目錄,或null,如果子進程應該繼承當前進程的工作目錄。
返回值
該方法返回一個新的Process對象,用於管理子進程
異常
SecurityException -- 如果安全管理器存在,並且其checkExec方法不允許創建子進程
IOException -- 如果發生I/ O錯誤
NullPointerException -- 如果命令爲null,或者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 file with the working directory we wish File dir = new File("C:/"); // create a process and execute notepad.exe and currect environment Process process = Runtime.getRuntime().exec("notepad.exe", null, dir); // print another message System.out.println("Notepad should now open."); } catch (Exception ex) { ex.printStackTrace(); } } }
讓我們來編譯和運行上面的程序,這將產生以下結果:
Executing notepad.exe... Notepad should now open.