2013-07-17 59 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

相關問題