Execute with parameters

batch-file, java

Solution

Windows:

ProcessBuilder pb = new ProcessBuilder(
        "cmd", "/c", "mybat.bat", 
        "param 1", "param 2", "param 3");

Unix:

ProcessBuilder pb = new ProcessBuilder(
        "sh", "mybat.sh", 
        "param 1", "param 2", "param 3");

Problem

I'm having difficulty executing a batch file in Java that expects parameters. These parameters may contain spaces so I need to wrap them in quotes. I will also need to do the same thing for Linux because some of the parameters may contain special characters such as `!`. Non-functional Windows code: ``` ProcessBuilder pb = new ProcessBuilder( "cmd", "/c", "\"mybat.bat\"", "\"param 1\"", "\"param 2\"", "\"param 3\"" ); ``` Non-functional Linux code: ``` ProcessBuilder pb = new ProcessBuilder( "bash", "-c", "'myshellscript.sh'", "'param 1'", "'param 2'", "'param 3'" ); ``` I understand that I should be adding the parameters like the Windows example below, but this won't work with the spaces: ``` ProcessBuilder pb = new ProcessBuilder( "cmd", "/c", "mybat.bat param 1 param 2 param 3" ); ``` How should this be done?

Original source