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


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


描述

這個java.lang.Runtime.exec(String[] cmdarray)方法在單獨的進程中執行指定的命令和參數。這是一種方便的方法。調用 exec(cmdarray) 形式的行為與調用 exec(cmdarray, null, null) 完全相同。

聲明

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

public Process exec(String[] cmdarray)

參數

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

返回值

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

異常

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

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

  • NullPointerException− 如果命令為空

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

示例

此示例需要一個名為的文件example.txt在我們的 CLASSPATH 中包含以下內容 -

Hello World!

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

package com.tutorialspoint;

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] = "example.txt";

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

         // create a process and execute cmdArray
         Process process = Runtime.getRuntime().exec(cmdArray);

         // print another message
         System.out.println("example.txt should now open.");
      } catch (Exception ex) {
         ex.printStackTrace();
      }
   }
}

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

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

相關用法


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