【问题标题】:How can i get the console output generated by a exe file?如何获取由 exe 文件生成的控制台输出?
【发布时间】:2010-11-18 01:45:07
【问题描述】:

不使用重定向到文件 (">", ">>")

【问题讨论】:

    标签: java console


    【解决方案1】:
    Process p = Runtime.getRuntime().exec("executable.exec");
    
    BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
    
    String line;
    while ((line = input.readLine()) != null) {
      System.out.println(line);
    }
    

    【讨论】:

    • 您可能希望从 getOutputStream 或 getErrorStream 读取流而不是输入。
    • 应该是输入流。就是这样的命名约定。
    • 也许你应该在最后加上 p.waitFor() 什么的?
    • 是的,你应该在while循环之后添加p.waitFor()
    • 这个stackoverflow.com/a/18955510/185565 答案有一个小的 ShelExec 包装器来运行进程和“吞噬” io 流以防止挂起或泄漏。
    【解决方案2】:

    请注意,您应该同时使用 stdout 和 stderr,以防止阻塞。详情请见this answer

    请注意,您可以只使用 stdout 而不是 stderr。但是,如果您的 .exe 在某些情况下生成错误,那么您的父进程可以阻止额外(意外)流数据。因此,最好同时运行您的流收集。

    【讨论】:

      【解决方案3】:

      如果您使用来自plexus-utils 的命令行类型,您可以避免很多与命令行交互相关的繁重工作,例如等待进程、转义参数等。如果需要,您也可以将命令设置为超时.

      您可以通过 StreamConsumers 来捕获 stdout 和 stderr,命令行处理会将输出一次传递给消费者。

      Commandline cl = new Commandline();
      
      cl.setExecutable( "dir" );
      
      cl.setWorkingDirectory( workingDirectory.getAbsolutePath() );
      
      cl.createArg().setValue( "/S" );
      
      StreamConsumer consumer = new StreamConsumer() {
          public void consumeLine( String line ) {
              //do something with the line
          }
      };
      
      StreamConsumer stderr = new StreamConsumer() {
          public void consumeLine( String line ) {
              //do something with the line
          }
      };
      
      int exitCode;
      
      try {
          exitCode = CommandLineUtils.execute( cl, consumer, stderr, getLogger() );
      } catch ( CommandLineException ex ) {
          //handle exception
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-07-04
        • 1970-01-01
        • 2021-06-05
        • 1970-01-01
        • 2014-08-25
        • 1970-01-01
        相关资源
        最近更新 更多