简体   繁体   English

交互式发送命令到java.lang.Process失败

[英]Interactively sending commands to java.lang.Process fails

I played around with executing windows processes (cmd.exe in this particular case) out of java and stumbled over a problem. 我试着用Java执行Windows进程(在这种情况下为cmd.exe),偶然发现了一个问题。 There is no reaction to the command net statistics server (and to no other command). 对命令net statistics server (以及其他命令)没有任何反应。

The examples I saw here on SO created the process with all the argument they needed. 我在SO上看到的示例使用所需的所有参数创建了流程。 But I would like to write directly to the output stream of the process. 但是我想直接写入过程的输出流。 So how can I do that? 那我该怎么办呢? What am I doing wrong? 我究竟做错了什么?

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

Only output is: 仅输出为:

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

PrintWriter will not write data to the OutputStream until its buffer is full. 在缓冲区已满之前, PrintWriter不会将数据写入OutputStream You can either flush manually 您可以手动冲洗

out.flush();

or use the constructor that uses autoflush 或使用使用自动刷新的构造函数

PrintWriter out = new PrintWriter(p.getOutputStream(), true);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM