【发布时间】:2018-11-30 15:23:35
【问题描述】:
我正在尝试从 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 脚本打印它的工作目录。 那个目录中是否有
*.doc等文件? -
不遗余力:你知道working目录是什么意思吗? IE。 不是脚本或二进制文件的位置。
-
使用 Cwd;我的 $dir = getcwd;这是获取工作目录的命令
-
如果你打印
$dir?从 Java 运行时,它会打印您期望的内容吗?