Home  >  Article  >  Java  >  How to execute external program such as Windows Media Player in Java?

How to execute external program such as Windows Media Player in Java?

WBOY
WBOYforward
2023-09-04 09:25:021127browse

如何在Java中执行外部程序,例如Windows Media Player?

Using the Runtime class

Java provides a class named java.lang.Runtime, which can be used to interact with the current environment.

getRunTime() The (static) methods of this class return the Runtime object associated with the current application.

The exec() method accepts a string value representing a command to execute a process in the current environment (system) and execute it.

Therefore, use the Runtime class to execute external applications -

  • Use the getRuntime() method to obtain the runtime object.
  • By passing its path as a string value to the exec() method.

Example

import java.io.IOException;
public class Trail {
   public static void main(String args[]) throws IOException {
      Runtime run = Runtime.getRuntime();
      System.out.println("Executing the external program . . . . . . . .");
      String file = "C:\Program Files\Windows Media Player\wmplayer.exe";
      run.exec(file);
   }
}

Output

System.out.println("Executing the external program . . . . . . . .

Using the ProcessBuilder class

Similarly, the constructor of the ProcessBuilder class Accepts a variable parameter of string type representing the command to execute the process and its parameters as parameters and constructs an object.

The start() method of this class starts/executes the process in the current ProcessBuilder. Therefore, to run an external program using the ProcessBuilder class-

  • Instantiate the ProcessBuilder class by passing the command to execute the process and its parameters as arguments to its constructor .

  • Execute the process by calling the start() method of the object created above.

Example

Real-time demonstration

import java.io.IOException;
public class ExternalProcess {
   public static void main(String args[]) throws IOException {
      String command = "C:\Program Files\Windows Media Player\wmplayer.exe";
      String arg = "D:\sample.mp3";
      //Building a process
      ProcessBuilder builder = new ProcessBuilder(command, arg);
      System.out.println("Executing the external program . . . . . . . .");
      //Starting the process
      builder.start();
   }
}

Output

Executing the external program . . . . . . . .

The above is the detailed content of How to execute external program such as Windows Media Player in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete