Search code examples
javawindowspowershellruntime.exec

Execute windows command in Java


Need to run netstat -n | find ":3389" | find "ESTABLISHED" command using Java Runtime.

Tried like: Runtime.getRuntime().exec(cmd); but we can't do this if we have | (pipe) in our command.

I had found for linux command we can costruct like: String[] cmd = {"/bin/sh", "-c", "grep -c 'Report Process started' /path/to/server.log"}; Runtime.getRuntime().exec(cmd); but I need for windows, please let me know how we can do?


Solution

  • You should run only netstat -n and do the rest in java. You could also write a script, and execute the script instead of separate commands. If you really need to do everything in a single line that has pipes the command must be prefixed with cmd /C