Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
280 views
in Technique[技术] by (71.8m points)

java - 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 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...