有人可以在下面的情景中帮助我,
我需要从我的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!";
提前致谢, Sudarsan
答案 0 :(得分:1)
在写入值后,您是否在Java上的OutputStream上调用flush()
?如果你不这样做,那么很有可能它们只会被保存在Java进程的流缓冲区中,所以永远不要把它放到Perl中(结果是两个进程最终都在等待对方的IO。)
(根据流的实现情况,这可能是必要的,也可能不是必需的,但它肯定不会受到伤害 - 我过去一直被这种情况所困扰。通常一个人不需要小心,因为在调用close()
时隐式发生刷新,但是在这里你不能在写完之后关闭流。)
答案 1 :(得分:1)
看起来您正在尝试阅读此代码中的完整一行:
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
...
但是,在您的perl代码中,您没有打印结束字符,因此readLine
永远不会返回(根据documentation)。