- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to execute an external program like windows media player in Java?
Using the Runtime class
Java provides a class named java.lang.Runtime, using this class you can interface with the current environment.
The getRunTime() (static) method of this class returns a Runtime object associated with the current application.
The exec() method accepts a String value representing the command to execute a process in the current environment (system) and executes it.
Therefore, to execute an external application using the Runtime class −
Get the run time object using the getRuntime() method.
Execute the required process by passing the path of it 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 arguments of type string representing the command to execute a process and its arguments as parameters and constructs an object.
The start() method of this class starts/executes the process(es) in the current ProcessBuilder. Therefore, to run an external program using the ProcessBuilder class −
Instantiate the ProcessBuilder class by passing the command to execute a process and arguments for it as parameters to its constructor.
Execute the process by invoking the start() method on the above created object.
Example
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 . . . . . . . .