从 java 程序调用 class 文件

invoking class file from java program

Similar question 这个问题在文件名与 class 路径方面存在问题。 我在我的程序中使用 classpath 但没有得到输出。

我通过各种帖子进行了很多搜索,但无法解决我的错误。 我的 D: 中有一个 class 文件,该文件只打印 "hello world".

当我通过命令提示符 运行 时:

java -cp D:/ Test

它工作正常。

但是当我 运行 在另一个 java 程序的主要方法中使用相同的方法时:

 Process p = Runtime.getRuntime().exec("java -cp D:/ Test");

我没有输出,也没有错误。 有人可以帮我看看这里出了什么问题吗?

您需要从 Process 中获取 InputStream 并读取输入。

Process p = Runtime.getRuntime().exec("java -cp D:/ Test");

这将 运行 您编程,但您看不到输出。您需要从流程中获取输入,使用以下代码:

BufferedReader stdInput = new BufferedReader(new 
     InputStreamReader(p.getInputStream()));

BufferedReader stdError = new BufferedReader(new 
     InputStreamReader(p.getErrorStream()));

// read the output from the command
System.out.println("Here is the standard output of the command:\n");
String s = null;
while ((s = stdInput.readLine()) != null) {
    System.out.println(s);
}