开发者

Call "interactive" Perl script from Java

I want to call an "interactive" Perl script from a Java program. Just for the clarity, the other way around (from Perl to Java) is not good for me.

The script is interactive in the sense that it requires a small configuration dialog with the user. For example, calling the script in cmd.exe would lead to a dialog like:

Do you want to overwrite the old settings? [yes,no (default=no)]

and the user should choose between 开发者_如何学运维writing yes, no or nothing at all in the command line. And depending on the user choice another message would appear: "Do you want to...." and the user will respond etc etc. I think you got the picture.

My question is how can I have the same dialog with the user when the script is called in a Java program? I mean, how can I capture the script's questions to the user, show them to user and then send the user's answer (got in the Java program) to the script?

A simple Runtime.getRuntime().exec() doesn't work in this case.

Hope I expressed clear enough the question.

Thank you for your help!


You must use getInputStream/getOutputStream methods to get access to stdin and stdout of perl stript. You can read and write to these streams to simulate user's behavior

OutputStream stdin = null;
InputStream stderr = null;
InputStream stdout = null;
Process process = Runtime.getRuntime ().exec ("...");
stdin = process.getOutputStream ();
stderr = process.getErrorStream ();
stdout = process.getInputStream ();
// "write" the parms into stdin
String line = "data\n";   
stdin.write(line.getBytes());
stdin.flush();
stdin.close();
// clean up if any output in stdout
BufferedReader brCleanUp = 
  new BufferedReader (new InputStreamReader (stdout));
while ((line = brCleanUp.readLine ()) != null) {
  //System.out.println ("[Stdout] " + line);
}
brCleanUp.close();

// clean up if any output in stderr
brCleanUp = 
  new BufferedReader (new InputStreamReader (stderr));
while ((line = brCleanUp.readLine ()) != null) {
  //System.out.println ("[Stderr] " + line);
}
brCleanUp.close();


This is a job for Expect. In Java: ExpectJ, expect4j


If (1) your call is from Java to Perl, and (2) you are not parsing the Perl script itself, why not use a JOptionPane.showConfirmDialog() from the Java code? Shouldn't be a big deal if a Yes/No is all your are getting from the script. Whatever you are printing to display to the user can be included in that confirm dialog as a plain ASCII text, too.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜