Perl accepts a scipt via STDIN. After pressing CTRL-D perl knows the "End of Script". After doing so, the script is executed.
Now my question: I wand to do that from Java.
proc = Runtime.getRuntime().exec("perl", env);
commandChannel = new BufferedWriter(new OutputStreamWriter(proc.getOutputStream()));
responseChannel = new BufferedReader(new InputStreamReader(proc.getInputStream()));
InputStreamReader mymacro = new InputStreamReader(getClass().getResourceAsStream("macro.perl"));
char[] b = new char[1024];
int read;
try
{
while ((read = mymacro.read(b)) != -1)
{
commandChannel.write(b, 0, read);
}
commandChannel.flush();
PERL IS WAITING FOR END OF SCRIPT; ??
} ...
But this exactly what CTRL-D does: closing the STDIN of the process. So in your case closing the proc.getInputStream() is the appropriate action to have the expected behavior as you simulate it in the shell.
If you want to do "something else" just do it. Like writing a special command to your script via STDIN which then interprets it as such and jumps into another state or whatever is desired
this example does exactly what you need:
public class TestPl {
public static void main(String[] args) {
Process proc;
try {
proc = Runtime.getRuntime().exec("perl");
// a simple script that echos stdin.
String script = "my $s=<>;\n" +
"print $s;";
OutputStreamWriter wr = new OutputStreamWriter(proc.getOutputStream());
//write the script:
wr.write(script);
//signal end of script:
wr.write(4);
wr.write("\n");
//write the input:
wr.write("bla bla bla!!!");
wr.flush();
wr.close();
String output = readFromInputStream(proc.getInputStream());
proc.waitFor();
System.out.println("perl output:\n"+output);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static String readFromInputStream(InputStream inputStream) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
String line;
StringBuffer buff = new StringBuffer();
while ((line=br.readLine())!=null){
if (buff.length() > 0){
buff.append("\n");
}
buff.append(line);
}
br.close();
return buff.toString();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With