在 Java 中執行命令列

Sheeraz Gul 2023年1月30日 2022年4月27日
  1. 在 Java 中使用 Runtime.getRuntime().exec() 執行命令
  2. 在 Java 中使用 Process Builder 執行命令
在 Java 中執行命令列

本文演示瞭如何在 Java 中執行命令並顯示輸出。

在 Java 中使用 Runtime.getRuntime().exec() 執行命令

Runtime.getRuntime().exec() 是 Java 執行命令的內建功能。

例子:

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

上面的程式碼通過 Runtime.getRuntime().exec() 執行命令,並使用使用者定義的函式 Show_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),

輸出將與命令列中的相同。ping www.delftstack.com 的請求超時。

在 Java 中使用 Process Builder 執行命令

Process Builder 庫還用於在 Java 中執行命令。

例子:

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

上面的程式碼使用 Process Builder 功能執行命令 java -version

輸出:

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)

程序構建器開啟 cmd 然後執行給定的命令。

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