Java 运行时执行输出
我想执行另一个文件中存在的类方法。我正在做以下工作:Java 运行时执行输出,java,process,runtime,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\
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\u Project\\src
替换为C:/Users/96171/eclipse workspace/IR\u 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);
}
}
执行程序
测试的输出流将成为当前程序运行java\u程序的输入流。将代码更改为此,然后尝试:
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 UTIL。您遇到了什么错误?@user12377884没有错误,但输出没有打印谢谢,如果其他程序打印了几行,我将如何读取打印出来的所有行??BufferedReader br=new BufferedReader(new InputStreamReader(process.getInputStream())
和br.readLine()
直到它为null
它在您通过进程时给出一个错误。getInputStream(),我使用了这个:非常感谢您的帮助!!你帮我省了很多工作!!