In the .NET framework, starting a process is achieved using System.Diagnostics.Process.Start("processname"). This allows users to easily launch any executable available on their system. But how can we achieve the same functionality in Java?
Java provides the Runtime.exec() method to launch external processes. It takes a command as a string argument and returns a Process object that represents the running process. Similar to .NET's Process.Start(), Runtime.exec() allows users to initiate applications independent of the operating system.
To demonstrate process invocation in Java, consider the following code:
import java.io.BufferedReader; import java.io.InputStreamReader; import java.nio.file.Paths; public class CmdExec { public static void main(String[] args) { try { // Get the path to 'tree.com' (which displays the directory tree) String treePath = Paths.get(System.getenv("windir"), "system32", "tree.com").toString(); // Start the 'tree.com' process Process p = Runtime.getRuntime().exec(treePath); // Read and print the output of the process BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream())); String line; while ((line = input.readLine()) != null) { System.out.println(line); } } catch (Exception err) { err.printStackTrace(); } } }
This script demonstrates how to start an external process (tree.com in this case) and capture its output. The process launches regardless of the operating system, making it a portable solution.
For more information on process invocation in Java, refer to:
The above is the detailed content of How to Launch External Processes in Java?. For more information, please follow other related articles on the PHP Chinese website!