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

Perl Del Rey
  • 959
  • 1
  • 11
  • 25

1 Answers1

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.

Sunil Dabburi
  • 1,442
  • 12
  • 18
  • Thank you so much, what if the other program prints several lines, how will I read all the lines printed out ?? – Perl Del Rey Dec 06 '19 at 18:26
  • `BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));` and `br.readLine()` till it's `null` – Sunil Dabburi Dec 06 '19 at 19:04
  • It gives an error when u pass process.getInputStream(), I used this: https://stackoverflow.com/questions/4334808/how-could-i-read-java-console-output-into-a-string-buffer and thank you so much for the help!! You saved me lots of work!! – Perl Del Rey Dec 06 '19 at 19:13