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);
}
}
-
1What error did you get?user12377884– user123778842019年12月06日 14:44:53 +00:00Commented Dec 6, 2019 at 14:44
-
@user12377884 no error, but output is not printedPerl Del Rey– Perl Del Rey2019年12月06日 15:51:11 +00:00Commented Dec 6, 2019 at 15:51
1 Answer 1
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.
3 Comments
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream())); and br.readLine() till it's null