2013-07-17 63 views
-5

我正在通过Java运行perl脚本。代码如下所示。如何通过Java向Perl脚本提供命令行参数

try { 
    Process p = Runtime.getRuntime().exec("perl 2.pl"); 
    BufferedReader br = new BufferedReader(
           new InputStreamReader(p.getInputStream())); 
    System.out.println(br.readLine()); 
} catch (IOException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
} 

我的perl脚本是这样的方式,当我直接通过命令行运行它,它要求我提供输入文件。我的问题是我怎么能通过Java提供文件名到perl脚本?

+0

在'“perl 2.pl”'后面加上你的参数? – Shark

+0

重写您的perl脚本,将输入文件名作为命令行参数,而不是只从stdin请求名称? – geoffspear

+0

我也在“perl 2.pl”之后添加了我的参数,但它不起作用。其实我提供输入文件名到脚本。 – Chirag

回答

0

如果您不想在脚本中添加另一个命令行参数(这会更干净,更健壮),您需要写入脚本的stdin。

这段代码应该工作(Test.java):

import java.io.*; 

public class Test 
{ 
    public static void main(String[] args) 
    { 
     ProcessBuilder pb = new ProcessBuilder("perl", "test.pl"); 
     try { 
      Process p=pb.start(); 
      BufferedReader stdout = new BufferedReader( 
       new InputStreamReader(p.getInputStream()) 
      ); 

      BufferedWriter stdin = new BufferedWriter(
       new OutputStreamWriter(p.getOutputStream()) 
      ); 

      //write to perl script's stdin 
      stdin.write("testdata"); 
      //assure that that the data is written and does not remain in the buffer 
      stdin.flush(); 
      //send eof by closing the scripts stdin 
      stdin.close(); 

      //read the first output line from the perl script's stdout 
      System.out.println(stdout.readLine()); 

     } 
     catch (IOException e) 
     { 
      e.printStackTrace(); 
     } 
    } 
} 

为了测试它,你可以用这短短的perl脚本(test.pl):

$first_input_line=<>; 
print "$first_input_line" 

我希望帮助。请看下面的Stackoverflow article

* Jost

+0

你可以通过额外的通过将String参数添加到[ProcessBuilder](http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/ProcessBuilder.html)构造函数(例如'new ProcessBuilder (“myCommand”,“myArg1”,“myArg2”,“myArg3”)。 – Jost

相关问题