Java使用路径名中的空格执行命令 [英] Java execute a command with a space in the pathname
问题描述
如何执行路径名中有空格的Java System(shell)命令?
How can I execute a Java System (shell) command that has a space in the pathname?
我尝试过引号和反斜杠(),但是它不起作用。
I've tried putting quotes and a backslash (), But it does not work.
ln -s "dir1/dir2" "my\ dir/dir2"
推荐答案
到目前为止,最可靠的方法是使用 Runtime.exec(String [ ] cmdarray)。
By far the most reliable way is to use Runtime.exec(String[] cmdarray).
如果使用 Runtime.exec(String command),Java只在空格上拆分命令。
If you use Runtime.exec(String command), Java only splits the command on whitespace.
使用由调用new StringTokenizer(命令)创建的StringTokenizer将命令字符串分解为标记,而不进一步修改字符类别。然后,由tokenizer生成的标记以相同的顺序放置在新的字符串数组cmdarray中。
the command string is broken into tokens using a StringTokenizer created by the call new StringTokenizer(command) with no further modification of the character categories. The tokens produced by the tokenizer are then placed in the new string array cmdarray, in the same order.
或使用 ProcessBuilder 是这样的:
ProcessBuilder pb = new ProcessBuilder("ln", "-s", "dir1/dir2", "my dir/dir2");
Process p = pb.start();
这篇关于Java使用路径名中的空格执行命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!