【问题标题】:Runtime Exec output运行时执行输出
【发布时间】:2020-03-31 13:30:38
【问题描述】:

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

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 上是:

我尝试将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);
    }
}

【问题讨论】:

  • 你遇到了什么错误?
  • @user12377884 没有错误,但没有打印输出

标签: java process runtime


【解决方案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 common utils。

【讨论】:

  • 非常感谢,如果其他程序打印了几行怎么办,我将如何阅读所有打印出来的行??
  • BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));br.readLine() 直到 null
  • 通过 process.getInputStream() 时出错,我使用了这个:stackoverflow.com/questions/4334808/… 非常感谢您的帮助!你为我节省了很多工作!
猜你喜欢
  • 1970-01-01
  • 2017-05-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多