运行时执行输出

时间:2019-12-06 14:33:30

标签: java process runtime

我想执行另一个文件中存在的类方法。我正在执行以下操作:

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

但是它不起作用。但是在cmd上是:

enter image description here

我尝试将C:\\Users\\96171\\eclipse-workspace\\IR_Project\\src替换为C:/Users/96171/eclipse-workspace/IR_Project/src,但仍然没有任何内容输出到控制台。

这是另一个程序:


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

1 个答案:

答案 0 :(得分:1)

已执行程序test的输出流将成为您当前程序run_java_program的输入流。将您的代码更改为此,然后尝试:

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

我使用了Scanner,因为我知道它只返回一行。根据您的需要,您还可以使用apache通用工具。

相关问题