在Java中想要调用外部命令,则需使用Runtime。
Runtime rt = Runtime.getRuntime();
Process prc = Runtime.getRuntime().exec(cmd);
下面是执行Perl脚本的函数,返回Perl输出的字符串
public static String execPerl(String filename){
String cmd;
String msg = "";
String brs = "";
cmd = "perl " + filename;
try{
Process p = Runtime.getRuntime().exec(cmd);
InputStream ins = p.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(ins));
while((brs=br.readLine())!=null) {
msg += msg + brs ;
}
}catch(IOException e) {
return e.getMessage();
}
return msg;
}
如果Perl脚本为
print "hello pl";
调用execPerl后,返回hello pl