Reputation: 2455
I wrote a Java program that can execute another Java program during runtime. The program is as follows:
import java.io.*;
public class exec {
public static void main(String argv[]) {
int i = 5, j = 6, k = 7;
BufferedReader rd = new BufferedReader(new InputStreamReader(System.in));
try {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
System.out.println("Enter class name");
String s = br.readLine();
Process pro = Runtime.getRuntime().exec(s);
BufferedReader in = new BufferedReader(new InputStreamReader(pro.getInputStream()));
String line=null;
while((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
} catch(Exception err) {
err.printStackTrace();
}
}
}
If I execute this program it will prompt the user to enter any class name (Java program) to execute. This is being done using this piece of code Process pro=Runtime.getRuntime().exec(s);
.
Once the user enters the Java class name, I should be able to pass the values 5,6,7 to the Java class entered by the user. Only one value at a time should be passed and the square of that number should be calculated.
How can I do this?
Upvotes: 0
Views: 3273
Reputation: 7371
In the second program you can implement a Server Socket then in your first program you can write a Client Socket which sends messages to second application.
You can see the following documentation: http://download.oracle.com/javase/tutorial/networking/sockets/
Upvotes: 1
Reputation: 54705
You can pass the int argument to your second Java program as follows:
String[] cmd = { s, Integer.toString(n) };
Process pro=Runtime.getRuntime().exec(cmd);
... or as a single String
:
Process pro=Runtime.getRuntime().exec(String.format("%s %d", s, n);
Upvotes: 3