【问题标题】:Interactively sending commands to java.lang.Process fails以交互方式向 java.lang.Process 发送命令失败
【发布时间】:2013-09-03 12:34:28
【问题描述】:

我尝试从 java 中执行 windows 进程(在这种特殊情况下为 cmd.exe)并偶然发现了一个问题。 对命令 net statistics server 没有反应(对其他命令也没有反应)。

我在 SO 上看到的示例使用他们需要的所有参数创建了流程。但我想直接写入进程的输出流。那么我该怎么做呢?我做错了什么?

public class CmdExecutor
{

  public static void main(String[] args)
  {
    ProcessBuilder pb = new ProcessBuilder("cmd");
    pb.directory(new File("/"));
    Process p = null;
    try
    {
      p = pb.start();
    }
    catch (IOException e)
    {
      System.out.println(e.getMessage());
    }

    if (p != null)
    {
      Scanner s = new Scanner(p.getInputStream());
      PrintWriter out = new PrintWriter(p.getOutputStream());

      boolean commandSent = false;

      while (s.hasNext())
      {
        System.out.println(s.nextLine());
        if (!commandSent)
        {
          out.println("net statistics server");
          commandSent = true;
        }
      }
    }
  }
}

只有输出是:

Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. Alle Rechte vorbehalten.

【问题讨论】:

  • 如果我 flush println 之后的流,它可以工作。有没有不缓冲直接写入的OutputStream?

标签: java windows process cmd


【解决方案1】:

PrintWriter 不会将数据写入OutputStream,直到其缓冲区已满。您可以手动冲洗

out.flush();

或者使用使用autoflush

的构造函数
PrintWriter out = new PrintWriter(p.getOutputStream(), true);

【讨论】:

  • Thx,也发现我需要flush...但不知道自动刷新:)
猜你喜欢
  • 2016-10-06
  • 2011-12-18
  • 2021-12-31
  • 1970-01-01
  • 1970-01-01
  • 2017-07-05
  • 2021-10-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多