gpt4 book ai didi

java - 运行时执行输出

转载 作者:行者123 更新时间:2023-12-02 09:13:26 24 4
gpt4 key购买 nike

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

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

最佳答案

执行的程序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。

关于java - 运行时执行输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59215104/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com