3

我想从另一个使用运行 Java 程序ProcessBuilder

我使用了代码

Process pr = rt.exec("cmd /c cd C:\\Users\\naman\\Desktop & java CalculateSum");
BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
BufferedReader error = new BufferedReader(new InputStreamReader(pr.getErrorStream()));
BufferedWriter output= new BufferedWriter(new OutputStreamWriter(pr.getOutputStream()));
String line = null;

while ((line = input.readLine()) != null) {
    System.out.println(line);
}

output.write("10");
output.write("30");

while ((line = input.readLine()) != null) {
    System.out.println(line);
}

int exitVal = pr.waitFor();
System.out.println("Exited with error code " + exitVal);

CalculateSum 有以下代码:

System.out.print("Enter 1 st value : ");
a=Integer.parseInt(br.readLine());
System.out.print("\nEnter second number : ");
b=Integer.parseInt(br.readLine());
System.out.println("\nresult is : "+(a+b));

我的基本动机是从另一个 Java 程序运行一个 Java 程序。

注意:我不想使用命令行参数来获取输入。我也尝试过使用ProcessBuilder相同的目的,但这也没有用。

4

2 回答 2

1

You could use ExpectJ (http://expectj.sourceforge.net/) to talk to another program using standard input/output.

Use this instead of trixing with BufferedReader/BufferedWriter in your first code block:

ExpectJ expectinator = new ExpectJ(5);
Spawn shell = expectinator.spawn("cmd /c cd C:\\Users\\naman\\Desktop & java CalculateSum");

// Talk to it
shell.expect("Enter 1 st value");
shell.send("10\n");
shell.expect("Enter second value");
shell.send("30\n");
于 2012-12-04T12:47:16.230 回答
0

只是一味地猜测问题是什么,问题可能是潮红。

尝试System.out.flush();在CalculateSum 中每次打印后添加。

在第一个程序中,将换行符添加到您的 output.write 调用中,例如output.write("10\n");, 以及output.flush();之后。

于 2012-12-04T12:40:55.340 回答