我正在尝试从 Java 程序执行我的 Perl 脚本。我已经在我的计算机中安装了 Perl。下面是我的示例 Perl 文件 (test.pl
)。
#!/usr/bin/perl -w
use 5.010;
use strict;
use warnings;
use Path::Tiny;
use autodie;
my $dir = path("E:/perl/scripts");
my $file = $dir->child("file.txt");
my $file_handle = $file->openw_utf8();
my @list=('a', 'list', 'of', 'lines');
push @list,<*.doc>;
push @list,<*.pdf>;
push @list,<*.jpg>;
push @list,<*.pl>;
print "Value of list = @list \n";
这是我执行 Perl 脚本的 Java 代码。
Process process;
try {
process = Runtime.getRuntime().exec("cmd /c perl E:\\perl\\PerlCallbyServlet\\test.pl");
//process = Runtime.getRuntime().exec("perl E:\\perl\\PerlCallbyServlet\\test.pl");
process.waitFor();
if (process.exitValue() == 0) {
System.out.println("Command Successful");
try {
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("Command Failure");
}
} catch (Exception e) {
System.out.println("Exception: " + e.toString());
}
现在,当我尝试运行这个 Java 类时,我得到的输出低于结果。
Command Successful
Value of list = a list of lines
但是当我使用命令从命令提示符运行此脚本时
perl test.pl
我的输出如下:
Value of list = a list of lines one.doc test.pl photo.jpg
因此,我从 Java 程序执行的 Perl 脚本得到的输出与从命令提示符执行的输出不同。
最佳答案
您的 Perl 脚本未设置工作目录。我假设您要将目录 E:/perl/scripts
的内容添加到 @list
中。尝试添加到 Perl 脚本中:
chdir('E:/perl/scripts');
抱歉,我不使用Windows,所以我无法测试Windows下的路径是否正确。
关于java - 从 Java 程序调用时 Perl 脚本未完全执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53517204/