从java程序中调用其它程序.doc
文本预览下载声明
从java程序中调用其它程序? /developer/TechTips/1999/tt1214.html 讨论了RMI (Remote Method Invocation,远程方法调用)如何用于程序间通讯,另一个用于通讯的技术是Runtime.exec() 方法。你可以用这个方法从一个运行阿java程序中调用另一个程序。Runtime.exec 也允许你执行和程序相关的操作,例如控制程序的标准输入输出,等待程序的结束并得到它的退出状态。下面是一个简单的C程序,用来说明这些特性:#include stdio.hint main() {printf(testing );return 0;}这个程序写字符串testing到标准输出,然后用退出状态0终止程序。为了在java程序中执行这个简单的程序,先编译这个c程序:$ cc test.c -o test(译者注:对于linux用户,可以用gcc test.c ?o test,对应windows用户可以用相应的c语言编译程序编译成可执行程序test.exe) (你的 C 编译器可能要求不同的参数)然后使用下面的代码调用那个程序:import java.io.*;import java.util.ArrayList;public class ExecDemo {static public String[] runCommand(String cmd)throws IOException {// set up list to capture command output linesArrayList list = new ArrayList();// start command runningProcess proc = Runtime.getRuntime().exec(cmd);/**译者注:前面的声明应该改成java.lang.Process,即:java.lang.Process proc = Runtime.getRuntime().exec(cmd);如果不改的话可能编译不同通过,在译者的机器上使用jdk1.2,编译出现5个错误使用jdk1.4编译出现4个错误*/// get command′s output stream and// put a buffered reader input stream on itInputStream istr = proc.getInputStream();BufferedReader br =new BufferedReader(new InputStreamReader(istr));// read output lines from commandString str;while ((str = br.readLine()) != null)list.add(str);// wait for command to terminatetry {proc.waitFor();}catch (InterruptedException e) {System.err.println(process was interrupted);}// check its exit valueif (proc.exitValue() != 0)System.err.println(exit value was non-zero);// close streambr.close();// return list of strings to callerreturn (String[])list.toArray(new String[0]);}public static void main(String args[]) throws IOException {try {// run a commandString outlist[] = runCommand(test);// display its outputfor (int i = 0; i outlist.length; i++)System.out.println(outlist);}catch (IOException e) {System.err.println(e);}}}演示程序调用方法runCommand 实际运行程序。String outlist[] = runCommand(test);这个方法使用一个输入流钩取程序的输出流,因此它可以读取程序的输出,然后将之存入一个字符串列表。 InputStre
显示全部