Reputation: 1059
I want to execute a class method that is present in another file. I am doing the following:
import java.io.IOException;
public class run_java_program {
public static void main(String[] args) {
try {
Process process = Runtime.getRuntime().exec("java -cp C:\\Users\\96171\\eclipse-workspace\\IR_Project\\src test");
} catch (IOException e) {
e.printStackTrace();
}
}
}
But its not working. However on the cmd it is:
I tried replacing C:\\Users\\96171\\eclipse-workspace\\IR_Project\\src
with C:/Users/96171/eclipse-workspace/IR_Project/src
but still nothing is printed out to the console.
Here is the other program:
//import py4j.GatewayServer;
public class test {
public static void addNumbers(int a, int b) {
System.out.print(a + b);
}
// public static void addNumbers(int a, int b) {
// System.out.print(a + b);
// }
public static void main(String[] args) {
// GatewayServer gatewayServer = new GatewayServer(new test());
// gatewayServer.start();
// System.out.println("Gateway Server Started");
test t = new test();
t.addNumbers(5, 6);
}
}
Upvotes: 0
Views: 135
Reputation: 1472
The outputstream of the executed program test
would become the inputstream for your current program run_java_program
. Change your code to this and try:
import java.io.IOException;
public class run_java_program {
public static void main(String[] args) {
try {
Process process = Runtime.getRuntime().exec("java -cp C:\\Users\\96171\\eclipse-workspace\\IR_Project\\src test");
java.util.Scanner s = new java.util.Scanner(process.getInputStream());
System.out.println(s.nextLine());
} catch (IOException e) {
e.printStackTrace();
}
}
}
I used Scanner
as I know it returns only one line. Based on your need you can also use apache common utils.
Upvotes: 1