當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Java Java.lang.Runtime.exec()用法及代碼示例


描述

這個java.lang.Runtime.exec(String[] cmdarray, String[] envp, File dir)方法在具有指定環境和工作目錄的單獨進程中執行指定的命令和參數。給定一個字符串數組 cmdarray(代表命令行的標記)和一個字符串數組 envp(代表 "environment" 變量設置),此方法創建一個新進程來執行指定的命令。

啟動操作係統進程高度為 system-dependent。可能出錯的許多事情包括 -

  • 找不到操作係統程序文件。
  • 對程序文件的訪問被拒絕。
  • 工作目錄不存在。

在這種情況下,將拋出異常。異常的確切性質是 system-dependent,但它始終是 IOException 的子類。

聲明

以下是聲明java.lang.Runtime.exec()方法

public Process exec(String[] cmdarray, String[] envp, File dir)

參數

  • cmdarray- 包含要調用的命令及其參數的數組。

  • envp- 字符串數組,其中每個元素都具有格式名稱=值的環境變量設置,如果子進程應該繼承當前進程的環境,則為null。

  • dir- 子進程的工作目錄,如果子進程應該繼承當前進程的工作目錄,則為null。

返回值

此方法返回一個新的 Process 對象,用於管理子流程

異常

  • SecurityException− 如果安全管理器存在且其 checkExec 方法不允許創建子進程

  • IOException− 如果發生 I/O 錯誤

  • NullPointerException− 如果命令為空

  • IndexOutOfBoundsException− 如果 cmdarray 是一個空數組(長度為 0)

示例

此示例需要一個名為的文件test.txt在我們的 C:/文件夾中包含以下內容 -

Hello

下麵的例子展示了 lang.Runtime.exec() 方法的用法。

package com.tutorialspoint;

import java.io.File;

public class RuntimeDemo {

   public static void main(String[] args) {
      try {

      // create a new array of 2 strings
      String[] cmdArray = new String[2];

      // first argument is the program we want to open
      cmdArray[0] = "notepad.exe";

      // second argument is a txt file we want to open with notepad
      cmdArray[1] = "test.txt";

      // print a message
      System.out.println("Executing notepad.exe and opening test.txt");

      // create a file which contains the directory of the file needed
      File dir = new File("c:/");

      // create a process and execute cmdArray and currect environment
      Process process = Runtime.getRuntime().exec(cmdArray, null, dir);

      // print another message
      System.out.println("test.txt should now open.");

      } catch (Exception ex) {
         ex.printStackTrace();
      }
   }
}

讓我們編譯並運行上麵的程序,這將產生以下結果 -

Executing notepad.exe and opening test.txt
test.txt should now open.

相關用法


注:本文由純淨天空篩選整理自 Java.lang.Runtime.exec() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。