import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;/** * Created by sweet on 2017/9/25. */public class ExecuteShellComand { public static void main(final String[] args) throws IOException, InterruptedException { String s = null; try {// String[] arr = new String[]{"/bin/sh", "-c", "ls -l"}; // Linux String[] arr = new String[]{ "cmd.exe", "/c", "dir"}; // Windows Process p = Runtime.getRuntime().exec(arr); BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream())); BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream())); System.out.println("Here is the standard output of the command:\n"); while ((s = stdInput.readLine()) != null) { System.out.println(s); } System.out.println("Here is the standard error of the command (if any):\n"); while ((s = stdError.readLine()) != null) { System.out.println(s); } System.exit(0); } catch (IOException e) { System.out.println("exception happened - here's what I know: "); e.printStackTrace(); System.exit(-1); } }}复制代码
原文在 http://www.baeldung.com/run-shell-command-in-java https://alvinalexander.com/java/java-exec-system-command-pipeline-pipe