在@Tim示例的基础上,构建一个独立的方法:import java.io.BufferedReader;import java.io.File;import java.io.InputStreamReader;import java.util.ArrayList;public class Shell { /** Returns null if it failed for some reason. */ public static ArrayList<String> command(final String cmdline, final String directory) { try { Process process = new ProcessBuilder(new String[] {"bash", "-c", cmdline}) .redirectErrorStream(true) .directory(new File(directory)) .start(); ArrayList<String> output = new ArrayList<String>(); BufferedReader br = new BufferedReader( new InputStreamReader(process.getInputStream())); String line = null; while ( (line = br.readLine()) != null ) output.add(line); //There should really be a timeout here. if (0 != process.waitFor()) return null; return output; } catch (Exception e) { //Warning: doing this is no good in high quality applications. //Instead, present appropriate error messages to the user. //But it's perfectly fine for prototyping. return null; } } public static void main(String[] args) { test("which bash"); test("find . -type f -printf '%T@\\\\t%p\\\\n' " + "| sort -n | cut -f 2- | " + "sed -e 's/ /\\\\\\\\ /g' | xargs ls -halt"); } static void test(String cmdline) { ArrayList<String> output = command(cmdline, "."); if (null == output) System.out.println("\n\n\t\tCOMMAND FAILED: " + cmdline); else for (String line : output) System.out.println(line); }}(测试示例是命令,该命令按时间顺序递归地列出目录及其子目录中的所有文件。.)顺便说一句,如果有人能告诉我为什么我需要四个和八个反斜杠,而不是两个和四个linux命令,我可以学到一些东西。比我所计算的还要多出一层无法逃避的事情。编辑:刚刚在Linux上尝试了同样的代码,结果是我需要测试命令中的反斜杠的一半!(即:预期数字2和4)现在,这不再是一个奇怪的问题linux命令,而是一个可移植性问题。