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

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

  • 在调用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]  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)也是一样的咯?

  • 于是乎,我们可以这样写:

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

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

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

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

所以,无法使用全路径的时候,我们需要更改一下策略,把 路径 改到工作目录dir 中去,比如:

File dir = new File("/home/path/");

然后用其第6种重载方法,把dir作为第三个参数传入即可:

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

猜你喜欢

转载自www.cnblogs.com/gejuncheng/p/9201869.html