Some Perl strings will not run from Java Runtime.getRuntime (). Exec ()

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

Perl code:

#!/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", the contents of which are:

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

      

This means it $line = <$ds>

is not being executed correctly, but I do not know why.

Any idea?

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

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

+3


source to share


1 answer


It seems that the folder your Perl code is running from is not the same as the Cygwin and Java executable. So perl Script can't find your file.

You should add error checking to your Perl code and check the current working directory 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 will not get the expected results.

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

+2


source







All Articles