user3745870
user3745870

Reputation: 321

Not able to invoke Perl script from Java

I am trying to invoke Perl script from Java but seems like I am not able to do it.

Here is my Perl script which creates a file. It is a simple script.

use strict;
use warnings;
open(my $fh, '>', 'report.txt');
print $fh "My first report generated by perl\n";
close $fh;
print "done\n";

Here is my Java code which is invoking above Perl script.

package perlfromjava;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class PerlFromJava {

public static void main(String[] args) {
    try {

        String command = "perl $HOME/Documents/hello.pl";
        System.out.println(command);
        Process proc = Runtime.getRuntime().exec(command);
    } catch (IOException ex) {
        Logger.getLogger(PerlFromJava.class.getName()).log(Level.SEVERE, null, ex);
    }
}

}

When I am running Perl scrip from command like, it is working perfectly but when I am invoking Perl script from Java, report.txt file is not getting created.

Why is it happening?

Thanks

Upvotes: 1

Views: 452

Answers (2)

Madhawa Priyashantha
Madhawa Priyashantha

Reputation: 9900

actually your code is working .but the problem is the file created by perl is generated in where you run java file.if you are using a ide then file has surely created inside of that project folder .if you search "report.txt" you will find the file.to understand change your perl script to

use strict;
use warnings;
open(my $fh, '>', 'C:/Users/Madhawa.se/Desktop/js/report.txt');
print $fh "My first report generated by perl\n";
close $fh;
print "done\n";

intead give report.txt give full path where u like to create report.txt file in the perl script .and see it's working.

 try {

    String command = "perl C:\\Users\\Madhawa.se\\Desktop\\js\\mm.pl";
    Process process = Runtime.getRuntime().exec(command);
    process.waitFor();
    if (process.exitValue() == 0) {
        System.out.println("Command Successful");
    } else {
        System.out.println("Command Failure");
    }
} catch (Exception e) {
    System.out.println("Exception: " + e.toString());
}

Upvotes: 1

Elliott Frisch
Elliott Frisch

Reputation: 201537

You can't use the $HOME variable from the Java Runtime. In Java, you could use System.getenv("HOME") or the cross-platform System.getProperty(String) to get it, like

String command = "perl " + System.getProperty("user.home") 
        + "/Documents/hello.pl";

A list of available System Properties is included in The Java Tutorials.

Edit

Don't forget to wait for the Process to complete,

try {
    Process proc = Runtime.getRuntime().exec(command);
    proc.waitFor();
} catch (IOException e) {
    e.printStackTrace();
} catch (InterruptedException e) {
    e.printStackTrace();
}

Upvotes: 1

Related Questions