Home > Java > javaTutorial > body text

How to Execute System Commands and Interact with Other Applications in Java?

Patricia Arquette
Release: 2024-11-19 04:51:02
Original
867 people have browsed it

How to Execute System Commands and Interact with Other Applications in Java?

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

Usage:

  1. Paths.get() constructs a local path to the specified command using system properties (in this case, "tree.com").
  2. Runtime.getRuntime().exec() initiates the process with the provided path.

This approach allows you to run commands on any operating system, as long as you have the correct local path for the executable.

The above is the detailed content of How to Execute System Commands and Interact with Other Applications 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 Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template