Utilizing Java to Initiate Processes
In Java, you can start processes in a manner analogous to System.Diagnostics.Process.Start() in .Net. Similar to the .Net implementation, the Java equivalent allows you to specify the application to be launched, enabling the user to locate and execute the desired executable.
Solution:
To start a process in Java:
<br>import java.io.BufferedReader;<br>import java.io.InputStreamReader;<br>import java.nio.file.Paths;</p> <p>public class CmdExec {</p> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">public static void main(String[] args) { try { // The location of the 'tree' command may vary, depending on the system. // This code uses a path generator to find the file based on the user's environment variables. Process p = Runtime.getRuntime().exec( Paths.get(System.getenv("windir"), "system32", "tree.com /A").toString() ); 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(); } }
}
Additional Notes:
The above is the detailed content of How can I launch processes in Java?. For more information, please follow other related articles on the PHP Chinese website!