调用Runtime.getruntime 下的exec方法时,有",<,|时该怎么办?

今天写一个用到编译的程序,遇到了问题。html

  • 在调用runtime.exec("javac HelloWorld.java");运行完美,也就是有生成.class。
  • 而到了runtime.exec("java HelloWorld >> output.txt");却怎么也没法重定向输出,连output.txt文件也生成不了。
  • 测试"echo hello >> 1.txt" 也是不能够,甚是头疼,因而乎翻阅资料,这才发现了
  • 一个认识上的误区,就是exec(str)中 不能把str彻底看做命令行执行的command。尤为是str中不可包含重定向 ' < ' ' > ' 和管道符' | ' 。
  • 那么,遇到这样的指令怎么办呢?咱们接着往下看:

 

两种方法:

  • 一种是将指令写到脚本中,在runtime.exec()中调用脚本。这种方法避过了使用exec(),也是一种思路。

  • 还有一种方法,就是调用exec()的重载方法:咱们来重点看这种方法:

咱们先看一下官方doc[>link<]给咱们提供的重载方法:java

[java]  view plain  copy
 
  1. 1.    public Process exec(String command) throws IOExecption  
  2.   
  3. 2.    public Process exec(String command,String [] envp) throws IOExecption  
  4.   
  5. 3.    public Process exec(String command,String [] envp,File dir) throws IOExecption  
  6.   
  7. 4.    public Process exec(String[] cmdarray) throws IOExecption  
  8.   
  9. 5.    public Process exec(String[] cmdarray,String [] envp) throws IOExecption  
  10.   
  11. 6.    public Process exec(String[] cmdarray,String [] envp,File dir) throws IOExecption  

 

 

翻阅其文档,发现其重载方法4.exec(String []cmdarray) 最简便适合咱们,官方说4.exec() 与执行6.exec(cmdarray,null,null) 效果是同样的。那么5.exec.(cmdarray,null)也是同样的咯?api

  • 因而乎,咱们能够这样写:

runtime.exec( new String[]{"/bin/bash", "-c", "java HelloWorld >> output.txt"} );bash

runtime.exec( new String[]{"/bin/bash", "-c", "java HelloWorld >> output.txt"} ,null );oracle

runtime.exec( new String[]{"/bin/bash", "-c", "java HelloWorld >> output.txt"} ,null,null );测试

 

不过要注意,若是使用java /home/path/HelloWorld 时,' / '会被解析成 " . ",从而报出 “错误: 找不到或没法加载主类 .home.path.HelloWorld ”.spa

因此,没法使用全路径的时候,咱们须要更改一下策略,把 路径 改到工做目录dir 中去,好比:.net

File dir = new File("/home/path/");命令行

而后用其第6种重载方法,把dir做为第三个参数传入便可:htm

String []cmdarry ={"/bin/bash", "-c", "java HelloWorld >> output.txt"}

runtime.exec(cmdarry,null.dir);

固然echo , ls 等命令便不受' / '限制了。

*BTW,exec()取得返回值的标准用法详见:runtime.exec()的左膀右臂http://blog.csdn.net/timo1160139211/article/details/75050886

总结:

  1. 当命令中包含重定向 ' < ' ' > ' 和管道符' | ' 时,exec(String command)方法便不适用了,须要使用exec(String [] cmdArray) 或者exec(String []cmdarray,String []envp,File dir)来执行。

例如:

  1. exec("echo hello >> ouput.txt");
  2. exec("history | grep -i mvn");

应改成:

  1. exec( new String[]{"/bin/sh","-c","echo hello >> ouput.txt"});
  2. exec( new String[]{"/bin/bash","-c","history | grep -i mvn"},null);
相关文章
相关标签/搜索