欢迎来到天天文库
浏览记录
ID:34736933
大小:69.13 KB
页数:4页
时间:2019-03-10
《从java程序中调用其它程序》由会员上传分享,免费在线阅读,更多相关内容在工程资料-天天文库。
1、从java程序中调用其它程序 http://developer.java.sun.com/developer/TechTips/1999/tt1214.html讨论了RMI(RemoteMethodInvocation,远程方法调用)如何用于程序间通讯,另一个用于通讯的技术是Runtime.exec()方法。你可以用这个方法从一个运行阿java程序中调用另一个程序。Runtime.exec也允许你执行和程序相关的操作,例如控制程序的标准输入输出,等待程序的结束并得到它的退出状态。下面是一个简单的C程序,用来说明这些特性:#
2、includeintmain(){printf("testing");return0;}这个程序写字符串"testing"到标准输出,然后用退出状态0终止程序。为了在java程序中执行这个简单的程序,先编译这个c程序:$cctest.c-otest(译者注:对于linux用户,可以用gcctest.c?otest,对应windows用户可以用相应的c语言编译程序编译成可执行程序test.exe)(你的C编译器可能要求不同的参数)然后使用下面的代码调用那个程序:importjava.io.*;importj
3、ava.util.ArrayList;publicclassExecDemo{staticpublicString[]runCommand(Stringcmd)throwsIOException{//setuplisttocapturecommandoutputlinesArrayListlist=newArrayList();//startcommandrunningProcessproc=Runtime.getRuntime().exec(cmd);/**译者注:前面的声明应该改成java.lang.Process,即
4、:java.lang.Processproc=Runtime.getRuntime().exec(cmd);如果不改的话可能编译不同通过,在译者的机器上使用jdk1.2,编译出现5个错误使用jdk1.4编译出现4个错误*///getcommand´soutputstreamand//putabufferedreaderinputstreamonitInputStreamistr=proc.getInputStream();BufferedReaderbr=newBufferedReader(newInputStreamRe
5、ader(istr));//readoutputlinesfromcommandStringstr;while((str=br.readLine())!=null)list.add(str);//waitforcommandtoterminatetry{proc.waitFor();}catch(InterruptedExceptione){System.err.println("processwasinterrupted");}//checkitsexitvalueif(proc.exitValue()!=0)Syste
6、m.err.println("exitvaluewasnon-zero");//closestreambr.close();//returnlistofstringstocallerreturn(String[])list.toArray(newString[0]);}publicstaticvoidmain(Stringargs[])throwsIOException{try{//runacommandStringoutlist[]=runCommand("test");//displayitsoutputfor(int
7、i=0;i8、BufferedReader(newInputStreamReader(istr));Stringstr;while((str=br.readLine())!=null)list.add(str);在所有的输出都被读取后,调用waitFor等待程序终止,然后调用exitValue读取程序的退出状态值。如
8、BufferedReader(newInputStreamReader(istr));Stringstr;while((str=br.readLine())!=null)list.add(str);在所有的输出都被读取后,调用waitFor等待程序终止,然后调用exitValue读取程序的退出状态值。如
此文档下载收益归作者所有