Java execute a command with a space in the pathname

后端 未结 4 1738
悲&欢浪女
悲&欢浪女 2020-11-27 06:32

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.



        
4条回答
  •  鱼传尺愫
    2020-11-27 07:22

    Do you really need to execute it in a shell (e.g. do you need to shell expansion of things like ~ or *, etc)? If not, you could invoke ln directly:

    Process p =
        Runtime.getRuntime()
        .exec(new String[]{"/bin/ln","-s","dir1/dir2", "my\\ dir/dir2"});
    

    If you really need a shell, try this (this may need a little tweaking depending on how the shell processes the quotes):

    Process p =
        Runtime.getRuntime()
        .exec(new String[]{"/bin/sh", "-c", "ln -s \"dir1/dir2\" \"my\\ dir/dir2\""});
    

    Edit:

    I was under the impression the second path has a literal backslash in it. If it's not supposed to remove the \\ from the string literals above.

提交回复
热议问题