How to Run Command Line in Java

Sheeraz Gul Feb 02, 2024
  1. Use Runtime.getRuntime().exec() to Run Commands in Java
  2. Use the Process Builder to Run Commands in Java
How to Run Command Line in Java

This article demonstrates how to run commands and show output in Java.

Use Runtime.getRuntime().exec() to Run Commands in Java

The Runtime.getRuntime().exec() is a built-in functionality of Java to run commands.

Example:

import java.io.*;
public class cmd_class {
  public static void main(String[] args) throws Exception {
    Process runtime = Runtime.getRuntime().exec("ping www.delftstack.com");
    Show_Output(runtime);
  }
  public static void Show_Output(Process process) throws IOException {
    BufferedReader output_reader =
        new BufferedReader(new InputStreamReader(process.getInputStream()));
    String output = "";
    while ((output = output_reader.readLine()) != null) {
      System.out.println(output);
    }
  }
}

The code above runs a command through Runtime.getRuntime().exec() and shows the output using the user-defined function Show_Output().

Output:

Pinging www.delftstack.com [3.66.136.156] with 32 bytes of data:
Request timed out.
Request timed out.
Request timed out.
Request timed out.

Ping statistics for 3.66.136.156:
    Packets: Sent = 4, Received = 0, Lost = 4 (100% loss),

The output will be the same as in the command line. Request timed out for pinging www.delftstack.com.

Use the Process Builder to Run Commands in Java

The Process Builder library is also used to run commands in Java.

Example:

import java.io.*;

public class cmd_class {
  public static void main(String[] args) throws Exception {
    ProcessBuilder build_test = new ProcessBuilder("cmd.exe", "/c", "java -version");
    build_test.redirectErrorStream(true);
    Process p = build_test.start();
    Show_Results(p);
  }
  public static void Show_Results(Process p) throws IOException {
    BufferedReader output_reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String output = "";
    while ((output = output_reader.readLine()) != null) {
      System.out.println(output);
    }
  }
}

The code above runs the command java -version using the Process Builder functionality.

Output:

java version "17.0.2" 2022-01-18 LTS
Java(TM) SE Runtime Environment (build 17.0.2+8-LTS-86)
Java HotSpot(TM) 64-Bit Server VM (build 17.0.2+8-LTS-86, mixed mode, sharing)

The process builder opens the cmd then runs the given command.

Author: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook

Related Article - Java Command