【问题标题】:Runtime Exec seems to be ignoring apostrophesRuntime Exec 似乎忽略了撇号
【发布时间】:2015-10-24 12:32:01
【问题描述】:

一个简单的例子是尝试 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。所以它似乎忽略了撇号,只是寻找一个名为“目录”的目录。

代码:

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();
        }
     }
}

【问题讨论】:

    标签: java command


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2021-10-28
      • 2016-09-30
      • 2016-03-16
      • 2014-02-03
      • 2012-03-11
      • 2013-09-07
      • 2016-08-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多