Search code examples
javaruntime.exec

Call external script to execute


In my project i have imported perl scripts . so my project now contains:

  1. A class file consisting of java code to execute a task and
  2. A perl script , which need to be called in the above (1.) class.

The main operation i need to achieve is : i want to call the perl script present in the same project to execute in the mid of the java code.

something like this:

public class Demo_Java{

// ... 
    System.out.println("entered 1st###############");
    Process p = Runtime.getRuntime().exec("perl /javaProject/perlScript.pl");
    p.waitFor();
}

But this is not working , i simply mentioned it for illustrating the requirement..
Is there any way i can call the perl script into the java file ?

EDIT: I tried running the following code :

    process = Runtime.getRuntime().exec("perl C:/javaProject/perlScript.pl ");
    process.waitFor();
    if(process.exitValue() == 0)
    {
        System.out.println("Command execution passed");
    }
    else
    {
        System.out.println("Command execution Failed");
    }

and am getting error as -> command execution failed .. may be this is due to syntax error on Runtime.getRuntime().exec("perl C:/javaProject/perlScript.pl "); , is this correct format to write exec ?


Solution

  • You mention a "syntax error", which probably is the issue considering paths look like "C:\\path\\file" in Windows Java apps.

    what if i want to write qualified name of perl script imported in the java project like

    Perl is not "imported into" any Java project. Only Java classes are "imported".

    As far as Java is concerned, your script is just a plain text file on disk. It's the fact that you execute a OS command that it even knows that it is a script, and this relies on Perl being installed and the perl binary on your PATH, so it really isn't portable...

    That being said, Java has no concept of "fully-qualified" file names. It know about "absolute paths", though, which is what I think you mean. However, you should rely more on your classpath of the Java app, not the path on your specific machine.

    For example, Difference between getClass().getClassLoader().getResource() and getClass.getResource()?

    So, if you had your Perl file on the classpath, you would need to get the absolute path to it. Something along the lines of,

    String path = getClass().getResource("/script.pl").toString();
    Runtime.getRuntime().exec("perl " + path);