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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3