开发者

Execute with parameters

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 li开发者_如何学编程ke 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?


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");


No, you should not quote the args on *nix. Quoting is necessary on *nix in an interactive shell to prevent the shell misinterpreting them, but when launching a process directly a shell isn't involved. Hence no need to quote.

If you do include the quotes, the launched process will see them as part of its incoming arguments and do things like (for example) try to open filenames containing quotes.

You also do not want the "-c" argument to bash. That tells it to parse the next argument as a command line, but you're supplying a list of arguments. Remove the "-c" option and the excess quotes and it should work.

The proper Linux call would be:

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

Also not that if the file "myshellscript.sh" is executable and has the appropriate shebang line (e.g. "#!/bin/bash"), you do not need the "bash" argument either. This is preferrable because if the script is ever replaced with one written in a different language you won't have to update your calling app.

Likewise, on Windows, you shouldn't need the "cmd" and "/c" arguments. The process launcher / OS should handle launching the batch file (based on extension) automatically.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜