2

Windows 7 cmd has no trouble executing ping -n 5 127.0.0.1 > nul. Also, Runtime.getRuntime.exec(new String[]{"ping", "-n", "5", "127.0.0.1"}) works fine.

But Runtime.getRuntime.exec(new String[]{"ping", "-n", "5", "127.0.0.1", ">", "nul"}) fails with Bad parameter >. Why?

I'm using Java7 in Java6 mode.

Ulrich Scholz
  • 2,039
  • 4
  • 30
  • 51

2 Answers2

2

The > redirection is not part of the ping command, it is part of cmd itself. When exec() sees the > it tries to feed it to ping as an argument.

To get the same functionality, just read (and ignore) data from the InputStream from the Process exec return value.

Mel Nicholson
  • 3,225
  • 14
  • 24
1

Because > is not a valid argument for ping. When executed on the command prompt the > is interpreted as output direction, but when used from Runtime().exec() it is not interpreted and is passed to ping as an argument (hence the error message).

To capture the output (unintuitively) use Process.getInputStream() (an instance of Process is returned by Runtime.exec()).

hmjd
  • 120,187
  • 20
  • 207
  • 252