最近老是和Runtime.exec()打交道。遇到了不少麻烦。从网上搜了不少方法还好一一解决的。现在总结一下吧。 最经典的介绍Runtime.exec()的文章是 Michael C. Daconta 的When Runtime.exec() won’t好吧,他老人家还没有把Runtime.exec()的使用说完全。我来补充下吧。 Sun的doc里其实说明还有其他的用法: exec(String[] cmdarray, String[] envp, File dir) Executes the specified command and arguments in a separate process with the specified environment and working directory. 那个dir就是调用的程序的工作目录,这句其实还是很有用的。 Windows下调用程序 Process proc =Runtime.getRuntime().exec("exefile"); Linux下调用程序就要改成下面的格式 Process proc =Runtime.getRuntime().exec("./exefile"); Windows下调用系统命令 String [] cmd={"cmd","/C","copy exe1 exe2"}; Process proc =Runtime.getRuntime().exec(cmd); Linux下调用系统命令就要改成下面的格式 String [] cmd={"/bin/sh","-c","ln -s exe1 exe2"}; Process proc =Runtime.getRuntime().exec(cmd); Windows下调用系统命令并弹出命令行窗口 String [] cmd={"cmd","/C","start copy exe1 exe2"}; Process proc =Runtime.getRuntime().exec(cmd); Linux下调用系统命令并弹出终端窗口就要改成下面的格式 String [] cmd={"/bin/sh","-c","xterm -e ln -s exe1 exe2"}; Process proc =Runtime.getRuntime().exec(cmd); 还有要设置调用程序的工作目录就要 Process proc =Runtime.getRuntime().exec("exeflie",null, new File("workpath")); 当然最好的执行系统命令的方法就是写个bat文件或是shell脚本。然后调用,那样修改和实现就简点多了。 还有在在Java程序中截获控制台输出[转]这篇文章中有详细的如何在JTextArea中显示拦截的控制台输出。 JAVA现在执行外部命令,主要的方式,还是通过调用所以平台的SHELL去完成,WINDOWS下面就用CMD,LINUX或者是UNIX下面就用SHELL,下面演示一个对BAT文件的调用,并把结果回显到控制台上,其它的应用程序类。 说明: 一个调用SHELL执行外部 取得外部程序的输出流,采用适当的READER读回来,并显示出来就OK了 下面是源程序: Java代码 import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; public class JavaExeBat { public static void main(String[] args) { Process p; //test.bat中的命令是ipconfig/all String cmd="c:\\test\\test.bat"; try { //执行命令 p = Runtime.getRuntime().exec(cmd); //取得命令结果的输出流 InputStream fis=p.getInputStream(); //用一个读输出流类去读 InputStreamReader isr=new InputStreamReader(fis); //用缓冲器读行 BufferedReader br=new BufferedReader(isr); String line=null; //直到读完为止 while((line=br.readLine())!=null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } } } 执行结果如下: Windows IP Configuration Host Name . . . . . . . . . . . . : Mickey Primary Dns Suffix . . . . . . . : Node Type . . . . . . . . . . . . : Unknown IP Routing Enabled. . . . . . . . : No WINS Proxy Enabled. . . . . . . . : No DNS Suffix Search List. . . . . . : domain Ethernet adapter 本地连接: Connection-specific DNS Suffix . : domain Description . . . . . . . . . . . : Broadcom NetXtreme Gigabit Ethernet