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 -
By passing its path as a string value to the exec() method.
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); } }
System.out.println("Executing the external program . . . . . . . .
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.
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(); } }
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!