java - 从 Java 程序运行系统命令时无输出

标签 java stdio

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

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

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

最佳答案

该命令运行正常,只是未连接到控制台。

如果您想查看命令的输出,您必须自己打印它:

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

code taken from another answer

如果您想了解更多信息,请阅读 standard streams :

In computer programming, standard streams are preconnected input and output channels between a computer program and its environment (typically a text terminal) when it begins execution. The three I/O connections are called standard input (stdin), standard output (stdout) and standard error (stderr). - from Wikipedia

关于java - 从 Java 程序运行系统命令时无输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21952079/

相关文章:

C语言中printf函数的代码

c - fwite/putc 是如何写入磁盘的?

java - 为什么我收到 .format 错误? JAVA文件

java - 如何使用gmail smtp发送邮件Spring实现?

c - 我不明白 fgets 如何创建段错误

c - 存储分隔的字符串

c++ - 同一变量的测试打印似乎给出了不同的结果

java - SolrPing.进程: Checked exception is invalid for this method

java - Android - 类变量未及时分配 setOnItemSelectedListener 的值

java - 如何使用 EclipseLink 加入提取而不是选择提取?