Home > Java > javaTutorial > How can I launch processes in Java?

How can I launch processes in Java?

Barbara Streisand
Release: 2024-11-17 20:07:02
Original
362 people have browsed it

How can I launch processes in Java?

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();
    }
}
Copy after login

}

Additional Notes:

  • This solution uses Runtime.getRuntime().exec() to execute the process.
  • To find the local path for the executable, you can use System properties or similar methods.
  • Please note that the specific location of executables may vary across different operating systems.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template