Java Runtime exec() 方法



描述

Java Runtime exec(String command, String[] envp) 方法在单独的进程中使用指定的环境执行指定的字符串命令。这是一种便捷方法。形式为 exec(command, envp) 的调用与调用 exec(command, envp, null) 的行为完全相同。

声明

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

public Process exec(String command, String[] envp)

参数

  • command − 指定的系统命令。

  • envp − 字符串数组,每个元素都以 name=value 的格式包含环境变量设置,或者如果子进程应该继承当前进程的环境则为 null。

返回值

此方法返回一个新的 Process 对象,用于管理子进程

异常

  • SecurityException − 如果存在安全管理器并且其 checkExec 方法不允许创建子进程

  • IOException − 如果发生 I/O 错误

  • NullPointerException − 如果 command 为 null,或者 envp 的某个元素为 null

  • IllegalArgumentException − 如果 command 为空

示例:打开记事本应用程序

以下示例显示了 Java Runtime exec() 方法的使用。我们使用 exec() 方法为记事本可执行文件创建了一个 Process 对象。这将调用记事本应用程序。如果发生某些异常,则会打印相应的堆栈跟踪和错误消息。

package com.tutorialspoint;

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.

示例:打开计算器应用程序

以下示例显示了 Java Runtime exec() 方法的使用。我们使用 exec() 方法为 calc 可执行文件创建了一个 Process 对象。这将调用计算器应用程序。如果发生某些异常,则会打印相应的堆栈跟踪和错误消息。

package com.tutorialspoint;

public class RuntimeDemo {

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

         // print a message
         System.out.println("Executing calc.exe...");

         // create a process and execute calc.exe and currect environment
         Process process = Runtime.getRuntime().exec("calc.exe", null);

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

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

输出

让我们编译并运行以上程序,这将产生以下结果:

Executing calc.exe...
Calculator should now open.

示例:打开 Windows 资源管理器应用程序

以下示例显示了 Java Runtime exec() 方法的使用。我们使用 exec() 方法为 Windows 资源管理器可执行文件创建了一个 Process 对象。这将调用 Windows 资源管理器应用程序。如果发生某些异常,则会打印相应的堆栈跟踪和错误消息。

package com.tutorialspoint;

public class RuntimeDemo {

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

         // print a message
         System.out.println("Executing explorer.exe...");

         // create a process and execute calc.exe and currect environment
         Process process = Runtime.getRuntime().exec("explorer.exe", null);

         // print another message
         System.out.println("Windows Explorer should now open.");

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

输出

让我们编译并运行以上程序,这将产生以下结果:

Executing explorer.exe...
Windows Explorer should now open.
java_lang_runtime.htm
广告

© . All rights reserved.