Lucien
Lucien

Reputation: 451

Some Perl lines won't execute from Java Runtime.getRuntime().exec()

I have a strange behavior when calling a perl script from Java.

The perl code is:

#!/usr/bin/env perl
use warnings;

print "dada\n";
$file = "settings.txt";
open $ds, "<", $file;
print "doudou\n";

while ($line = <$ds>){
    print "$line\n";
    last if $. == 4;
}

print "dodo\n";
close $ds;

As you can see, in this code I want to read the file "settings.txt" which contents :

1 : a
2 : b
3 : c
4 : d

And this script works when called from cygwin and the output is :

dada
doudou
1 : a
2 : b
3 : c
4 : d
dodo

But when I call it from Java using the following code:

String line;
String cmd = "perl C:\\Data\\Tests\\match_settings.pl";

try {
    Process proc = Runtime.getRuntime().exec(cmd);
    BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
    while ((line = in.readLine()) != null) {
        System.out.println("Line :" + line);
    }
    in.close();
} catch (IOException a) {
    // TODO Auto-generated catch block
    a.printStackTrace();
}

Then when the Java function is executed, I get the output:

Line :dada
Line :doudou
Line :dodo

Which means that $line = <$ds> is not well executed, but I don't know why.

Any idea ?

Sorry for the long post, wanted to be as precise as possible.

PS : I know some of you are wondering "Why not read the settings.txt file by Java code himself ?" but that's not the question here ;)

Upvotes: 3

Views: 190

Answers (1)

AMDG
AMDG

Reputation: 975

It seems that the folder from which your perl code is executed is not the same when executing from Cygwin and Java. So the perl Script can't find your file.

You should add error checking in your perl code, and verify your current working dir directory.

I would write:

#!/usr/bin/env perl
use warnings;
use Cwd;

my $cwd = cwd();    

print "dada\n";
print "In folder: $cwd";
$file = "settings.txt";
open ($ds, "<", $file) || die "Can't open settings.txt. Error code: $!";
print "doudou\n";

while ($line = <$ds>){
    print "$line\n";
    last if $. == 4;
}

print "dodo\n";
close $ds;

This will help you debug why, when your script is executed from Java, you don't get the expected results.

You should also redirect stderr to stdout in your Java code, so you will get error lines.

Upvotes: 2

Related Questions