"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Execute System Commands and Interact with Other Applications in Java?

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

Published on 2024-12-28
Browse:538

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

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3