Stefan
Stefan

Reputation: 2613

How can I execute a Perl script from my Java program?

I am writing a little tool that needs to invoke a Perl script to do some stuff.

I already know and written the code on how to call it, but I have to provide the full-qualified path to the Perl script for the exec().

Is there any possibility to provide that script as a sort of package that can be invoked directly?

I want to generate an executable JAR later and want to also have the whole tool to provide the Perl script and not to know where it is located.

Currently its like:

private void extractAudioStream() {
    inputFile = "C:\\Users\\Stefan\\Documents\\temp_tshark\\forward_stream.pcap";
    outputFile_audiostream = "C:\\Users\\Stefan\\Documents\\temp_tshark\\forward_stream.pcm";

    String perl_cmd = "perl C:\\Users\\Stefan\\Documents\\tshark_bin\\rtp_dump.pl " + inputFile + " " + outputFile_audiostream;

    try {
        p = Runtime.getRuntime().exec(perl_cmd);

Hope question is clear enough.

I think this may not be as easy because the system perl command awaits the full-qualified path? Is there then any possibility to detect my current location and pass it to my cmd-String?

Upvotes: 0

Views: 7303

Answers (3)

Dan Berindei
Dan Berindei

Reputation: 7204

String perl_cmd = "perl -e \"print \\\"bla\\n\\\";\";"
Runtime.getRuntime().exec(perl_cmd);

Edit: I forgot to put a space between -e and the script; you also have to escape backslashes and double-quotes in your script (twice if you're the script inline in Java instead of reading it from a jar file), which makes things a little awkward for more than one-liners.

So it would probably be better to use Process.getOutputStream to write the script to the Perl interpreter's standard input:

  String perlScript = "print \"hello\";"; // get from a jar with Class.getResourceAsStream()
  Process p = new ProcessBuilder("perl").redirectErrorStream(true).redirectOutput(ProcessBuilder.Redirect.INHERIT).start();
  BufferedWriter w = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
  w.write(perlScript);
  w.close();
  p.waitFor();

Upvotes: 2

sergio
sergio

Reputation: 69047

if you read/store your perl script in a string, you can execute it like this:

perlScript = "print \"HELLO\\n\"; print \"CIAOOOO\\n\";";
String perl_cmd = "echo \"" + perlScript + "\" |perl";
Runtime.getRuntime().exec(perl_cmd);

Hope it helps...

Upvotes: 1

Will Hartung
Will Hartung

Reputation: 118804

You can write the script out to a file, say a temporary file, and execute it from there, then delete it when you're done.

Upvotes: 0

Related Questions