2

I know very well how to execute commands via Runtime.getRuntime().exec(command) and handle the output, but this is VERY limited.

Take Windows for example (Vista specifically but that shouldn't matter).

How can I execute commands like 'echo', 'cd', 'md', 'rd', and any other command rooted inside of the cmd.exe through ProcessBuilder (or whatever class) in Java?

bgroenks
  • 1,859
  • 5
  • 34
  • 63
  • ProcessBuilder is the correct class (http://download.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.html). Is there something specific you are having trouble accomplishing? – kylewm Nov 18 '11 at 23:28
  • It's worth noting that each of the commands you have listed are able to be done through the Java libraries. I know you might not have every function you need, but I would recommend using the Java libraries whenever you can, resorting to ProcessBuilder to do it only when necessary. – corsiKa Nov 18 '11 at 23:41
  • @glowcoder Of course. They were only examples of commands rooted inside of the actual command prompt and not the system itself. I won't be using any of those particular commands to carry out actual programmatic tasks. That would be silly. Java has the ability to do so. If you must know, I just need Java to be able to execute all/most native commands from a Command Shell Wrapper I am making. – bgroenks Nov 19 '11 at 03:52
  • @KyleMahan Yes. Making a Command Shell Wrapper. Basically a command prompt run by Java with a GUI. Mainly for use on some particular UNIX machines on which I can't access the terminal. – bgroenks Nov 19 '11 at 03:53
  • For anyone else looking at this, you can make a custom wrapper or use Apache Commons exec: https://commons.apache.org/proper/commons-exec/tutorial.html – Deepak Feb 22 '18 at 20:18

2 Answers2

4

You just call cmd /c dir rather than just dir in Runtime.exec or ProcessBuilder or some other way to run external applications in JAVA.

manojlds
  • 290,304
  • 63
  • 469
  • 417
  • Thanks! Would you happen to know the equivalent on UNIX? – bgroenks Nov 19 '11 at 03:24
  • Just for the use of anyone who happens to see this answer, the equivalent in on *nix systems would be: `sh -c ` Although, I would recommend Apache Commons Exec or something similar to take care of all of this for you. – bgroenks Jan 03 '17 at 23:45
0

Another trick is to leverage the Ant libraries and put together a programmed version of <exec ...> (Ant Exec Task). This also gives you access to all kinds of Ant-supported input/output processing and filtering.

This is not writing an Ant XML script here, but calling Ant from your code.

mgaert
  • 2,338
  • 21
  • 27