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

How can I launch processes in Java?

Barbara Streisand
Barbara StreisandOriginal
2024-11-17 20:07:02298browse

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>
<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:

  • 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!

Statement:
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