2

我正在使用 Java 类在 Linux 机器上执行 Perl 脚本。.class正在成功创建。但是当我执行这个类时,它说exit code successful as sop,但我看不到 Perl 输出或脚本的执行。如果我直接执行 Perl,它工作正常......

这是 Perl 脚本:

#!/usr/local/bin/perl

print ("Enter the distance to be converted:\n"); 
$originaldist = <STDIN>;
chop ($originaldist);
$miles = $originaldist * 0.6214;
$kilometers = $originaldist * 1.609;
print ($originaldist, " kilometers = ", $miles,   " miles\n");

这是我调用脚本的 Java 类:

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;

class test {
    public static void main(String[] args) throws IOException {
        String[] aCmdArgs = { "perl", "-e"
                  , "pl newprg.pl" };
        Runtime oRuntime = Runtime.getRuntime();
        Process oProcess = null;
        try {
            oProcess = oRuntime.exec(aCmdArgs);
            oProcess.waitFor();
        } catch (Exception e) {
            System.out.println("error executing " + aCmdArgs[0]);
        }
        /* dump output stream */
        BufferedReader is = new BufferedReader
            ( new InputStreamReader(oProcess.getInputStream()));
        String sLine;
        while ((sLine = is.readLine()) != null) {
            System.out.println(sLine);
        }
        System.out.flush();
        /* print final result of process */
        System.err.println("Exit status=" + oProcess.exitValue());
        return;
    }
}
4

1 回答 1

1

两个问题:

  • perl -e pl newprg.pl实际上不会从命令行执行您的程序,因为它将无法解析给定的(非)表达式。您可能打算使用perl newprg.pl
  • 您的程序需要输入,您需要使用进程的输出流将其输入

例如:

try {
    oProcess = oRuntime.exec(aCmdArgs);
    PrintWriter writer = new PrintWriter(new OutputStreamWriter(
            oProcess.getOutputStream()));
    writer.println(200);
    writer.close();
    oProcess.waitFor();
} catch (Exception e) {
    System.out.println("error executing " + aCmdArgs[0]);
}
于 2013-04-09T06:04:39.617 回答