Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

controlling a java program from another

Tags:

java

I want to run a Java program from another using ProcessBuilder

I used the code

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 has following code:

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));

My basic motivation is to run a Java program from another Java program.

NOTE: I don't want to use command line arguments to take input. Also I have tried using ProcessBuilder for the same purpose, but that also did not work.

like image 949
Naman Kapoor Avatar asked Mar 16 '26 03:03

Naman Kapoor


1 Answers

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");
like image 174
Markus Avatar answered Mar 18 '26 16:03

Markus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!