-5

I am running perl script through Java. The code is as shown below.

try {
    Process p = Runtime.getRuntime().exec("perl 2.pl");
    BufferedReader br = new BufferedReader(
                               new InputStreamReader(p.getInputStream()));
    System.out.println(br.readLine());
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

My perl script is in such way that when I run it directly through command line it ask me to supply input file. My question is how could I supply file name to perl script through Java?

Maroun
  • 94,125
  • 30
  • 188
  • 241
Chirag
  • 455
  • 1
  • 4
  • 18

1 Answers1

0

If you don't want to add another command line argument to your script (which is much cleaner and more robust) you need to write to the script's stdin.

This snippet should work (Test.java):

import java.io.*;

public class Test
{
    public static void main(String[] args)
    {
        ProcessBuilder pb = new ProcessBuilder("perl", "test.pl");
        try {
            Process p=pb.start();
            BufferedReader stdout = new BufferedReader( 
                new InputStreamReader(p.getInputStream())
            );

            BufferedWriter stdin = new BufferedWriter(
                new OutputStreamWriter(p.getOutputStream())
            );

            //write to perl script's stdin
            stdin.write("testdata");
            //assure that that the data is written and does not remain in the buffer
            stdin.flush();
            //send eof by closing the scripts stdin
            stdin.close();

            //read the first output line from the perl script's stdout
            System.out.println(stdout.readLine());

        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}

To test it you can use this short perl script (test.pl):

$first_input_line=<>;
print "$first_input_line"

I hoped that helped. Please also have a look at the following Stackoverflow article.

*Jost

Community
  • 1
  • 1
Jost
  • 1,549
  • 12
  • 18
  • You can pass additional command line arguments to the script by adding String arguments to the [ProcessBuilder](http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/ProcessBuilder.html) constructor (e.g. `new ProcessBuilder("myCommand", "myArg1", "myArg2", "myArg3")`. – Jost Jul 17 '13 at 12:54