想从Java调用一个linux shell命令

我正尝试使用redirect(>&)和pipe道(|)从Java执行一些Linux命令。 Java如何调用cshbash命令?

我试图用这个:

 Process p = Runtime.getRuntime().exec("shell command"); 

但是它不兼容redirect或pipe道。

exec不会在你的shell中执行一个命令

尝试

 Process p = Runtime.getRuntime().exec(new String[]{"csh","-c","cat /home/narek/pk.txt"}); 

代替。

编辑::我没有csh在我的系统,所以我用bash代替。 以下为我工作

 Process p = Runtime.getRuntime().exec(new String[]{"bash","-c","ls /home/XXX"}); 

使用ProcessBuilder来分隔命令和参数而不是空格。 这应该工作,不pipe使用的shell:

 import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class Test { public static void main(final String[] args) throws IOException, InterruptedException { //Build command List<String> commands = new ArrayList<String>(); commands.add("/bin/cat"); //Add arguments commands.add("/home/narek/pk.txt"); System.out.println(commands); //Run macro on target ProcessBuilder pb = new ProcessBuilder(commands); pb.directory(new File("/home/narek")); pb.redirectErrorStream(true); Process process = pb.start(); //Read output StringBuilder out = new StringBuilder(); BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream())); String line = null, previous = null; while ((line = br.readLine()) != null) if (!line.equals(previous)) { previous = line; out.append(line).append('\n'); System.out.println(line); } //Check result if (process.waitFor() == 0) { System.out.println("Success!"); System.exit(0); } //Abnormal termination: Log command parameters and output and throw ExecutionException System.err.println(commands); System.err.println(out.toString()); System.exit(1); } } 

以@ 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); } } 

(testing示例是一个按时间顺序recursion列出目录及其子目录中的所有文件的命令 。)

顺便说一下,如果有人能告诉我为什么我需要四个和八个反斜杠,而不是两个和四个,我可以学到一些东西。 还有一个层面的问题比我所计算的还要多。

编辑:只是在Linux上试了这个相同的代码,结果certificate我在testing命令中需要一半的反斜杠! (即:预期的二,四)。现在它不再是奇怪的,这是一个可移植性的问题。