Java将命令传递给终端区别

时间:2014-05-19 04:49:40

标签: java terminal command difference

我想谈谈Java中的cordova程序。在终端我可以这样做以获得版本:

cordova -v

并在终端返回:

3.4.1-0.1.0

但如果我要求Java运行cordova -v它返回错误:java.io.IOException: Cannot run program "cordova": error=2, No such file or directory.  我在终端试了这个:

/usr/local/bin/cordova -v
and it still returned:
3.4.1-0.1.0

但当我要求Java运行/usr/local/bin/cordova -v时,它并没有返回任何。解决了我的问题?

修改

粘贴评论

我正在调用我的runShell函数,如

runShell("cordova -v"); 

private String runShell(String command) { 
   StringBuffer output = new StringBuffer(); 
   Process p; 
   try { 
       p = Runtime.getRuntime().exec(command); 
       p.waitFor(); 
       BufferedReader reader = 
           new BufferedReader(new InputStreamReader(p.getInputStream()));
       String line = "";     
       while ((line = reader.readLine())!= null) { 
           output.append(line + "\n"); 
       }  
   } catch (Exception e) { 
       System.out.println(e); return "Error: " + e; 
   }

   return output.toString(); 
}

1 个答案:

答案 0 :(得分:0)

你想要

Runtime.getRuntime().exec(new String[]{ "/usr/local/bin/cordova", "-v" });

您必须单独传递命令及其每个参数,因为您没有调用shell来为您解析命令行。