Whenever in doubt, always consult the API:
java.lang.Process
The ProcessBuilder.start()
and Runtime.exec
methods create a native process and return an instance of a subclass of Process
that can be used to control the process and obtain information about it. The class Process
provides methods for performing input from the process, performing output to the process, waiting for the process to complete, checking the exit status of the process, and destroying (killing) the process.
Runtime.exec(String command)
Executes the specified system command in a separate process.
So yes, Runtime.exec
can execute a command that you'd usually type in the system command prompt. This is hardly a platform-independent solution, but sometimes it's needed. The returned Process
object lets you control it, kill it, and importantly sometimes, redirect its standard input/output/error streams.
Related questions
API links
notepad.exe example
As mentioned before, this is platform dependent, but this snippet works on my Windows machine; it launches notepad.exe
, and attempts to open test.txt
from the current working directory. The program then waits for the process to terminate, and prints its exit code.
public class ExecExample {
public static void main(String[] args) throws Exception {
Process p = Runtime.getRuntime().exec("notepad.exe test.txt");
System.out.println("Waiting for notepad to exit...");
System.out.println("Exited with code " + p.waitFor());
}
}