Search code examples
javaprocesscommand-execution

Is java Runtime.exec(String[]) platform independent?


I had some code that ran commands through Runtime.getRuntime.exec(String), and it worked on Windows. When I moved the code to Linux, it broke, and the only way of fixing it was to switch to the exec(String[]) version. If I leave things this way, will the code work the same on Windows and Linux, or should I use the exec(String) on Windows and exec(String[]) on Linux?


Solution

  • Use String[] on both.

    The answer I gave you before was the result of several miserable hours of debugging a production software running on windows.

    After a lot of effort we ( I ) came to the solution posted before ( use String[] )

    Since the problems you've got were on Linux, I guess using the array on both will be the best.

    BTW. I tried that method with Java 1.4, Since then a new class is available: ProcessBuilder added on Java1.5. I'm not sure what is that all about, but there should be a good reason for it. Take a look at it and read what the difference between that an Runtime.exec is. Probably it will be a better option.

    Finally some commands won't work on either platform because they are built in with the shell ( either Windows cmd or bash/sh/ etc ) such as dir or echo and some of those. So I would recommend do extra/extra test on each target platform and add exception handlers for the unsupported commands.

    :)