[Java SE] Java執行命令行

1 序言

  • 執行命令行,是實現自動化程序跨環境調用的重要途徑

2 源碼示例

package test.java;

import org.junit.Test;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @author johnny-zen
 * @version v1.0
 * @create-time 2023/8/25 11:38
 * @description ...
 * @refrence-doc
 *  [1] 如何在 Java 中運行命令行 - 火焰兔 - https://www.zadmei.com/rhzjzyxm.html
 * @gpt-promt
 */

public class ExecuteCommandTest {
    @Test
    public void processTest(){
        String command = "jps -l";// jps -l / java -verbose
        try {
            // 創建一個 Runtime 實例
            Runtime runtime = Runtime.getRuntime();
            // 執行命令行命令
            Process process = runtime.exec(command);

            // 獲取命令行輸出結果
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            // 等待命令行執行完畢
            int exitCode = process.waitFor();
            System.out.println("finished to execute the command, and the exit code : " + exitCode);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void processBuilderTest(){
        try {
            // 指定要執行的命令或可執行文件及其參數
            List<String> command = Arrays.asList("ping","www.baidu.com");
            //List<String> command = Arrays.asList("cmd.exe", "/c", "dir");

            // 創建一個 ProcessBuilder 實例
            ProcessBuilder processBuilder = new ProcessBuilder(command); //new ProcessBuilder("dir", "-l");

            // 設置工作目錄(可選)
            //String workingDirectory  = "C:\\Users\\408675\\Desktop";
            //processBuilder.directory(new File(workingDirectory));

            // 啓動進程
            Process process = processBuilder.start();

            // 獲取命令行輸出結果 (可選)
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "GBK"));// Windows CMD 默認以 GBK 字符集 編碼文本
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }

            // 獲取環境信息 (可選)
            // eg: <key: JAVA_HOME, value: D:\Program\Java\jdk1.8.0_261> ...
            //Map<String, String> environment =  processBuilder.environment();
            //environment.entrySet().forEach(varEntry -> {
            //    System.out.println(String.format("<key: %s, value: %s>", varEntry.getKey(), varEntry.getValue()));
            //});

            // 獲取命令行輸出 | 等待外部進程結束
            int exitValue = process.waitFor();
            System.out.println("finished to execute the command, and the exit code : " + exitValue);

            // 關閉進程
            process.destroy();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}
  • output

processTest()

9984 org/netbeans/Main
22180 org.jetbrains.jps.cmdline.Launcher
22244 com.intellij.rt.junit.JUnitStarter
31268 sun.tools.jps.Jps
18424 D:\Program\DBeaver-23-0-4\dbeaver\plugins\org.eclipse.equinox.launcher_1.6.400.v20210924-0641.jar
27368 org.jetbrains.jps.cmdline.Launcher
11788 cn.xxx.bd.datasource.biz.DataSourceApplication
6604 org.jetbrains.idea.maven.server.RemoteMavenServer36
finished to execute the command, and the exit code : 0

processBuilderTest()

D:\Program\Java\jdk1.8.0_261\bin\java.exe -ea -Didea.test.cyclic.buffer.size=1048576 "-javaagent:D:\Program\IDEA\IDEA_COMMUNITY 2022.2\lib\idea_rt.jar=61044:D:\Program\IDEA\IDEA_COMMUNITY 2022.2\bin" -Dfile.encoding=UTF-8 -classpath C:\Users\xxxx\AppData\Local\Temp\classpath2097328303.jar com.intellij.rt.junit.JUnitStarter -ideVersion5 -junit4 test.java.ExecuteCommandTest,processBuilderTest

正在 Ping www.baidu.com [120.232.145.144] 具有 32 字節的數據:
來自 120.232.145.144 的回覆: 字節=32 時間=44ms TTL=48
來自 120.232.145.144 的回覆: 字節=32 時間=44ms TTL=48
來自 120.232.145.144 的回覆: 字節=32 時間=45ms TTL=48
來自 120.232.145.144 的回覆: 字節=32 時間=44ms TTL=48

120.232.145.144 的 Ping 統計信息:
    數據包: 已發送 = 4,已接收 = 4,丟失 = 0 (0% 丟失),
往返行程的估計時間(以毫秒爲單位):
    最短 = 44ms,最長 = 45ms,平均 = 44ms
<key: USERDOMAIN_ROAMINGPROFILE, value: XXXX>
...

3 參考文獻

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章