Ulrich Scholz
Ulrich Scholz

Reputation: 2111

command works in Windows cmd but fails with Runtime.getRuntime.exec()

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.

Upvotes: 2

Views: 1128

Answers (2)

hmjd
hmjd

Reputation: 121971

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()).

Upvotes: 1

Mel Nicholson
Mel Nicholson

Reputation: 3225

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.

Upvotes: 2

Related Questions