0

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:

enter image description here

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);
 }
}
asked Dec 6, 2019 at 14:33
2
  • 1
    What error did you get? Commented Dec 6, 2019 at 14:44
  • @user12377884 no error, but output is not printed Commented Dec 6, 2019 at 15:51

1 Answer 1

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.

answered Dec 6, 2019 at 16:57
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you so much, what if the other program prints several lines, how will I read all the lines printed out ??
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream())); and br.readLine() till it's null
It gives an error when u pass process.getInputStream(), I used this: stackoverflow.com/questions/4334808/… and thank you so much for the help!! You saved me lots of work!!

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.