mike
mike

Reputation: 5055

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. There is no reaction to the command net statistics server (and to no other command).

The examples I saw here on SO created the process with all the argument they needed. 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.

Upvotes: 0

Views: 118

Answers (1)

Reimeus
Reimeus

Reputation: 159864

PrintWriter will not write data to the OutputStream until its buffer is full. You can either flush manually

out.flush();

or use the constructor that uses autoflush

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

Upvotes: 3

Related Questions