终端命令执行工具

演示代码如下

    public static void main(String[] args) throws IOException, InterruptedException {
        String[] execute = ExecUtil.execute("ls -lh");
        for (String s : execute) {
            System.out.println(s);
        }
    }

输出如下

total 64
-rw-r--r--  1 dingqianwen  staff    11K May 29  2022 LICENSE
-rw-r--r--  1 dingqianwen  staff    80B May 29  2022 pi4j-demo.iml
-rw-r--r--  1 dingqianwen  staff    13K Jun  4  2022 pom.xml
drwxr-xr-x  3 dingqianwen  staff    96B May 29  2022 src
drwxr-xr-x  8 dingqianwen  staff   256B May 29  2022 target

实现代码如下


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class ExecUtil
{
    public static String[] execute(String command) throws IOException, InterruptedException {
        return execute(command, null);
    }

    public static String[] execute(String command, String split) throws IOException, InterruptedException {
        List<String> result = new ArrayList<>();

        // create external process
        Process p = Runtime.getRuntime().exec(command);

        // wait for external process to complete
        p.waitFor();

        // if the external proess returns an error code (non-zero), then build out and return null
        if(p.exitValue() != 0) {
            p.destroy();
            return null;
        }

        // using try-with-resources to ensure closure
        try(InputStreamReader isr = new InputStreamReader(p.getInputStream());
            BufferedReader reader = new BufferedReader(isr)) {
            // read lines from buffered reader
            String line = reader.readLine();
            while (line != null) {
                if (!line.isEmpty()) {
                    if (split == null || split.isEmpty()) {
                        result.add(line.trim());
                    } else {
                        String[] parts = line.trim().split(split);
                        for(String part : parts) {
                            if (part != null && !part.isEmpty()) {
                                result.add(part.trim());
                            }
                        }
                    }
                }

                // read next line
                line = reader.readLine();
            }
        }

        // destroy process
        p.destroy();

        // return result
        if (result.size() > 0) {
            return result.toArray(new String[result.size()]);
        } else {
            return new String[0];
        }
    }
}

源码:com.pi4j.util.ExecUtil

更新日期:
作者: dingqw