【问题标题】:No output when running system commands from a Java program从 Java 程序运行系统命令时没有输出
【发布时间】:2014-02-22 08:58:03
【问题描述】:

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

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

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

【问题讨论】:

    标签: java stdio


    【解决方案1】:

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

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

    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

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

    【讨论】:

    • 或许可以解释如何将其连接到控制台,或以其他方式查看输出。
    【解决方案2】:

    试试这个

     String command="java -cp 1outinstr;out Main"
        Process p = Runtime.getRuntime().exec( // "cmd - for windows only"
                            "cmd /c " + command);
        BufferedReader in = new BufferedReader( new InputStreamReader(p.getInputStream()))
        while(in.readline != null)
        {
        String output = in.readline();
        System.out.println(output);
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-06
      • 2014-10-27
      • 1970-01-01
      • 2020-09-26
      • 2021-07-26
      • 2012-04-10
      • 1970-01-01
      • 2023-04-05
      相关资源
      最近更新 更多