Running Processes in Java
In Java, the ability to launch processes is a crucial feature for executing system commands and interacting with other applications. To initiate a process, Java provides an equivalent to the .Net System.Diagnostics.Process.Start method.
Solution:
Obtaining a local path is crucial to execute processes in Java. Luckily, Java's System properties offer ways to determine this path. The following code snippet demonstrates how to launch a process in Java:
import java.io.BufferedReader; import java.io.InputStreamReader; import java.nio.file.Paths; public class CmdExec { public static void main(String args[]) { try { // Enter code here Process p = Runtime.getRuntime().exec( Paths.get(System.getenv("windir"), "system32", "tree.com /A").toString() ); // Enter code here try (BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()))) { String line; while ((line = input.readLine()) != null) { System.out.println(line); } } } catch (Exception err) { err.printStackTrace(); } } }
Usage:
This approach allows you to run commands on any operating system, as long as you have the correct local path for the executable.
The above is the detailed content of How to Execute System Commands and Interact with Other Applications in Java?. For more information, please follow other related articles on the PHP Chinese website!