执行外部 Java 代码并获得输出

Execute external Java code and get output

我想从另一个Java 程序 中执行Java CLI 程序并获取CLI 程序的输出。我已经尝试了两种不同的实现方式(使用 runtime.exec()ProcessBuilder),但它们不太有效。

这是特殊的部分; 当执行诸如 pwd 之类的命令时,实现工作(捕获输出),但由于某种原因,它们不捕获使用 [=17= 执行的 Hello World java 程序的输出].

执行代码:

public static void executeCommand(String command)
{
    System.out.println("Command: \"" + command + "\"");

    Runtime runtime = Runtime.getRuntime();
    try
    {
        Process process = runtime.exec(command);

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

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

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

        // read any errors from the attempted command
        System.out.println("Standard error of the command (if any):\n");
        while ((s = stdError.readLine()) != null) {
            System.out.println(s);
        }
    } catch (Exception e)
    {
        e.printStackTrace();
    }
}

示例输出

Command: "cd /Users/axelkennedal/Desktop && java Hello"
Standard output of the command:

Standard error of the command (if any):

Command: "pwd"
Standard output of the command:

/Users/axelkennedal/Dropbox/Programmering/Java/JavaFX/Kode
Standard error of the command (if any):

我已经验证 Hello 确实在 运行 Hello 时直接从 CLI 而不是通过 executeCommand() 向 CLI 打印 "Hello world"。

你好世界

public class Hello
{
    public static void main(String[] args)
    {
        System.out.println("Hello world!");
    }
}

这个"cd /Users/axelkennedal/Desktop && java Hello"不是一条命令,而是两条命令,中间用&&隔开。一般来说,这意味着执行第一个命令,如果第一个命令成功,则执行第二个命令。您不能将其作为单个命令传递,但您可以自己实现逻辑:

例如执行"cmd1 && cmd2"

if (Runtime.getRuntime().exec("cmd1").waitFor() == 0) {
    Runtime.getRuntime().exec("cmd2").waitFor();
}

但是,因为在本例中cmd1是改变目录,所以有一个更好的方法,即使用ProcessBuilder的目录功能,而不是第一个命令。

Process p = new ProcessBuilder("java","hello")
        .directory(new File("/Users/axelkennedal/Desktop"))
        .start();