3

I am new to perl but have done some programming in java facing a problem in running the perl script present in the jar file .

I am using windows and I have written a perl script to convert one type of file to another type .

I have checked the perl script with the java program using the Runtime and I am able to run the same as required and i am getting the output converted files as well (using the cmd line)

I have created a GUI in java to get the files to convert to the target files . I am able to run the file from netbeans IDE as will .

But when I am trying to run the jar file .

I am using URL to get the URL to the perl script .

URL url = this.getClass().getResource("/com/MyProject/FileConverter/fileconverter.pl");

and Runtime for Executing the script :

String[] cmd = {"perl",path,input_file,output_file};
process = Runtime.getRuntime().exec(cmd);

Please help in resolving the issue . Basically i do need to know how we can run the perl script present in the same jar file that we are executing.

Miller
  • 34,962
  • 4
  • 39
  • 60
milan kumar
  • 226
  • 2
  • 16

2 Answers2

3

You will have to read that perl file as resource and write it somewhere on file system as File (like this) and then pass that path to your command


See Also

Community
  • 1
  • 1
jmj
  • 237,923
  • 42
  • 401
  • 438
3

I'm assuming you have your perl script file in you jar and you don't want to extract it, just execute it "from inside".

One solution is to get the "stream" of your "resource" (your perl script), and then execute "perl" writing your script in the process' standard input.

This is better explained with a piece of code:

IMPORTANT CAVEAT: the path to your script in getResourceAsStream shouldn't start with /

// Start the process "perl"
Process process = Runtime.getRuntime().exec("perl");

// get the script as an InputStream to "inject" it to perl's standard input
try (
        InputStream script = ClassLoader.getSystemClassLoader()
              .getResourceAsStream("com/MyProject/FileConverter/fileconverter.pl");
        OutputStream output = process.getOutputStream()
) {

    // This is to "inject" your input and output file,
    // as there is no other easy way ot specify command line arguments
    // for your script
    String firstArgs = "$ARGV[0] = \"" + input_file + "\";\n" +
                       "$ARGV[1] = \"" + output_file + "\";\n";
    output.write(firstArgs.getBytes());


    // send the rest of your cript to perl
    byte[] buffer = new byte[2048];
    int size;
    while((size = script.read(buffer)) != -1) {
        output.write(buffer, 0, size);
    }
    output.flush();

}

// just in case... wait for perl to finish
process.waitFor();
morgano
  • 17,210
  • 10
  • 45
  • 56