Runtime Exec 似乎忽略了撇号

Runtime Exec seems to be ignoring apostrophes

一个简单的例子是尝试 cd 到一个包含两个以上单词的目录。当我 运行 下面的代码时,我没有得到预期的错误:/usr/bin/cd: line 2: cd: /Directory With Two Words: No such file or directory,而是这个错误:/usr/bin/cd: line 2: cd: '/Directory: No such file or directory。所以它似乎忽略了撇号,只是在寻找一个名为 "Directory".

的目录

代码:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Test
{
     public static void main(String []args)
     {
        try 
        {
            Process p = Runtime.getRuntime().exec("cd '/Directory With Two Words'");
            BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));

            // read any errors from the attempted command
            System.out.println("Error:");
            String s = null;
            while ((s = stdError.readLine()) != null) 
            {
                System.out.println(s);
            }
        }
        catch (IOException e) 
        {
             e.printStackTrace();
        }
     }
}

您应该使用 exec(String[]) 方法,它更安全。所以这应该在没有引号或撇号的情况下工作:

Runtime.getRuntime().exec(new String[] {"cd", "/Directory With Two Words"});

JavaWorld 上的优秀文章也值得一看 When Runtime.exec() won't