0

I have class that invokes perl script:

Runtime.getRuntime().exec(perlscript.pl)

The class and the script are placed on the same jar archive. This jar was built by maven. And perl script was placed in root of the jar, but the class not in root path.

When I launch the perl script I get error: "The system cannot find the file specified"

Where should I place the script to properly invoke it?

Willis V
  • 153
  • 1
  • 8

2 Answers2

1

This works both, in Eclipse and as a Maven-built jar. Following what is said in this SO answer, what I've done is (i) find the original script within the jar, (ii) copy its content into a newly created file within a temporary folder and finally (iii) -- execute that script:

// find the original script within the JAR, 
// mine sits in /src/main/resources/Perl/Hello.pl
InputStream in = PerlCaller.class.getClass().getResourceAsStream("/Perl/Hello.pl");
// if the file in the jar's root
// InputStream in = PerlCaller.class.getClass().getResourceAsStream("/Hello.pl");
if (null == in) {
  System.err.println("Resource ws not found, exiting...");
  System.exit(10);
}

// copy its content into a temporary file, I use strings since it's a script
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
File scriptFile = File.createTempFile("perlscript", ".pl");
BufferedWriter bw = new BufferedWriter(new FileWriter(scriptFile));
String line;
while ((line = reader.readLine()) != null) {
  bw.write(line + "\n");
}
bw.close();

// execute the newly created file
String[] command = { "perl", scriptFile.getAbsolutePath() };

final ProcessBuilder pb = new ProcessBuilder(command);
pb.redirectErrorStream(true);
final Process p = pb.start();

BufferedReader outputReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
StringBuilder builder = new StringBuilder();
String outputLine = null;
while ((outputLine = outputReader.readLine()) != null) {
  builder.append(outputLine);
  builder.append(System.getProperty("line.separator"));
}
String scriptOutput = builder.toString();

System.out.println(scriptOutput);

Hope this helps!

Community
  • 1
  • 1
seninp
  • 712
  • 1
  • 6
  • 23
0

You can access you script as a stream like:

Thread.currentThread().getContextClassLoader().getResourceAsStream("script.pl");

if your script is not in the root of classpath, use slashes to point to it like:

"path/to/script/script.pl"

dimplex
  • 494
  • 5
  • 9