从Java程序运行系统命令时没有输出

2 java stdio

这是尝试运行系统命令的代码:

String command = "java -cp 1outinstr;out Main";
Process p      = Runtime.getRuntime().exec("cmd /c " + command);
Run Code Online (Sandbox Code Playgroud)

我的问题是我看不到命令​​的输出.

cor*_*zza 5

命令运行正常,它只是没有连接到控制台.

如果要查看命令的输出,则必须自己打印:

String command = "java -cp 1outinstr;out Main";
Process p = Runtime.getRuntime().exec("cmd /c " + command);

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

// read any errors from the attempted command
System.out
        .println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
    System.out.println(s);
}
Run Code Online (Sandbox Code Playgroud)

代码来自另一个答案

如果您想了解更多信息,请阅读标准流:

在计算机编程中,标准流是计算机程序与其环境(通常是文本终端)在开始执行时预先连接的输入和输出通道.三个I/O连接称为标准输入(stdin),标准输出(stdout)和标准错误(stderr). - 来自维基百科

  • 也许提供一个解释*如何*将它连接到控制台,或以另一种方式查看输出. (3认同)