在@Tim示例的基礎(chǔ)上,構(gòu)建一個獨立的方法: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命令,我可以學(xué)到一些東西。比我所計算的還要多出一層無法逃避的事情。編輯:剛剛在Linux上嘗試了同樣的代碼,結(jié)果是我需要測試命令中的反斜杠的一半!(即:預(yù)期數(shù)字2和4)現(xiàn)在,這不再是一個奇怪的問題linux命令,而是一個可移植性問題。