如果您不想在脚本中添加另一个命令行参数(更简洁、更健壮),则需要写入脚本的标准输入。
这个片段应该可以工作(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 文章。
*约斯特