【发布时间】:2011-10-03 00:41:07
【问题描述】:
有人可以在以下情况下帮助我吗,
我需要从我的 java 代码中调用 perl 脚本。 perl 脚本是一个交互式代码,它在执行过程中从用户那里获取输入并继续到结束。因此,我使用的示例是,执行时的 perl 脚本通过在控制台中打印“你多大了?”来询问年龄,当用户输入一些值说“26”时。然后它会打印“哇!你已经 26 岁了!”。
当我尝试从我的 java 代码中调用此脚本时,该过程一直等到我在输出流中将值设为 26,而在输入流中没有值。最后,当我再次阅读输入流时,我将脚本的整个输出放在一起。那么,我不能让它互动吗?
我浏览了许多论坛和博客,但找不到任何符合我要求的论坛和博客。
这里是java代码
import java.io.*;
public class InvokePerlScript {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Process process;
try
{
process = Runtime.getRuntime().exec("cmd /c perl D:\\sudarsan\\eclips~1\\FirstProject\\Command.pl");
try {
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
out.write("23");
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
process.waitFor();
if(process.exitValue() == 0)
{
System.out.println("Command Successful");
try {
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
else
{
System.out.println("Command Failure");
try {
BufferedReader in = new BufferedReader(new InputStreamReader(process.getErrorStream()));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
catch(Exception e)
{
System.out.println("Exception: "+ e.toString());
}
}
}
Perl 代码如下
$| = 1;
print "How old are you? \n";
$age = <>;
print "WOW! You are $age years old!";
提前致谢, 苏达山
【问题讨论】:
-
请发布您正在使用的 java 和 perl 代码。
-
听起来你有缓冲问题。您是否尝试在 perl 中将
$|设置为非零以刷新输出? -
在添加 $|=1 之后这也不起作用:-(
标签: java perl integration