Pass a string with multiple contiguous spaces as a parameter to a jar file using Windows command prompt called from a java program

戏子无情 提交于 2019-12-05 21:59:02

Necro but: don't use the Runtime.exec(String) overload. Per the javadoc (indirectly) it tokenizes the command at any whitespace ignoring the quoting rules that would apply if you entered this command line directly via CMD (or a Unix shell). The Windows executor then rebuilds the command line from the tokens, with your extra spaces lost.

Instead use the String[] overload with the correct parsing:

 p = runtime.exec(new String[]{"cmd","/c","java","-cp",classpath,classname,"hello   world"});

or you don't actually use any feature of CMD here so you don't need it:

 p = runtime.exec(new String[]{"java","-cp",classpath,classname,"hello   world"});

If you use ProcessBuilder instead, its ctor and .command(setter) are declared as String... (vararg) so you can just pass the tokens without writing new String[]{...}.

Alternatively, run CMD and give it the commandline as input:

 p = runtime.exec("cmd"); // or new ProcessBuilder + start 
 String line = "java -cp " + classpath + " " + classname + " \"hello   world\"\n";
 p.getOutputStream.write(line.getBytes());

(For this approach the output from CMD will include banner, prompt, and echo of the input.)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!