Running Perl-Script with Java (embedded in Perl)

Perl accepts the script through STDIN. After pressing CTRL-D, perl knows "End Script". After that, the script is executed.

Now my question is: I will do this using Java.

  • Perl Open Process
  • Copy script to STDIN Perl-Process
  • HOW I SIGNED PERCEL CRTL-D WITHOUT CLOSING THE FLOW (from inside java)
  • Send some input to Script
  • get some output from script.

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; ??
}  ...
+5
source share
2 answers

But this is exactly what CTRL-D does: close the STDIN process. Therefore, in your case, closing proc.getInputStream () is the appropriate action for the expected behavior when you simulate it in a shell.

- , . script STDIN, ,

+1

, :

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();
}

}

+1

All Articles