Java Runtime exec() 方法



描述

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

声明

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

public Process exec(String command)

参数

command − 指定的系统命令。

返回值

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

异常

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

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

  • NullPointerException − 如果 command 为 null。

  • IllegalArgumentException − 如果 command 为空。

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

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

package com.tutorialspoint;

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
         Process process = Runtime.getRuntime().exec("notepad.exe");

         // 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() 方法为计算器可执行文件创建了一个 Process 对象。这将调用计算器应用程序。如果发生某些异常,则会打印相应的堆栈跟踪以及错误消息。

package com.tutorialspoint;

public class RuntimeDemo {

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

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

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

         // 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() 方法为 explorer 可执行文件创建了一个 Process 对象。这将调用 explorer 应用程序。如果发生某些异常,则会打印相应的堆栈跟踪以及错误消息。

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 explorer.exe
         Process process = Runtime.getRuntime().exec("explorer.exe");

         // 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.