Home > Java > javaTutorial > How to Launch External Processes in Java?

How to Launch External Processes in Java?

DDD
Release: 2024-11-17 21:55:02
Original
632 people have browsed it

How to Launch External Processes in Java?

Launching External Processes in Java

In the .NET framework, starting a process is achieved using System.Diagnostics.Process.Start("processname"). This allows users to easily launch any executable available on their system. But how can we achieve the same functionality in Java?

Java Process Invocation

Java provides the Runtime.exec() method to launch external processes. It takes a command as a string argument and returns a Process object that represents the running process. Similar to .NET's Process.Start(), Runtime.exec() allows users to initiate applications independent of the operating system.

Code Example

To demonstrate process invocation in Java, consider the following code:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.file.Paths;

public class CmdExec {

  public static void main(String[] args) {
    try {
      // Get the path to 'tree.com' (which displays the directory tree)
      String treePath = Paths.get(System.getenv("windir"), "system32", "tree.com").toString();

      // Start the 'tree.com' process
      Process p = Runtime.getRuntime().exec(treePath);

      // Read and print the output of the process
      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

This script demonstrates how to start an external process (tree.com in this case) and capture its output. The process launches regardless of the operating system, making it a portable solution.

Additional Resources

For more information on process invocation in Java, refer to:

  • [Java Documentation on Runtime.exec()](http://www.rgagnon.com/javadetails/java-0014.html)
  • [Retrieving System Properties in Java](http://download.oracle.com/javase/tutorial/essential/environment/sysprop.html)

The above is the detailed content of How to Launch External 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template