java与shell相互嵌套调用注意事项

来源:互联网 发布:海康威视 算法研究院 编辑:程序博客网 时间:2024/05/16 17:57

java与shell相互嵌套调用


因为要迭代的处理某些日志文件和相关数据,java需要与shell相互嵌套调用,在数据量较小,运行时间短,输出的日志少的时候,相互调用能够很愉快的合作,哥正高兴呢,但是后来一旦数据量大起来,处理时间一长就会出现一些不合理的现象不是异常后台根本不会报错,你是在逗我玩么?),但是进程就是不继续往下走,好奇怪,哥试了好几次,都是这样!!!


后来通过查代码和资料(http://stackoverflow.com/),发现是 Runtime.exec() 这个方法有大坑!下面且听我一一道来:

Runtime.exec()共有6种方法,我使用的是最后一种方法:如下图:


刚开始我的编码如下:



可能是因为把

  int extValue = process.waitFor();  


  while ((line = input.readLine()) != null){
                    log.info("-----  :  "+line);
                    list.add(line);
                }

写反了,应该把int extValue = process.waitFor();  写在while后面(我猜的,这样可以将系统的缓存及时清除掉,就不会造成死锁了)


后来看到一个更高级的,

StreamGobbler是一个线程,及时清除Runtime.exec() 这个方法调用shell产生的标准输出的文件,这样就不会将缓存占满,造成死锁。

代码如下:



StreamGobbler代码如下:

import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.io.PrintWriter;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;public class StreamGobbler extends Thread {public static Log log = LogFactory.getLog(StreamGobbler.class); InputStream is;      String type;      OutputStream os;       public  StreamGobbler(InputStream is, String type) {          this(is, type, null);      }      public  StreamGobbler(InputStream is, String type, OutputStream redirect) {          this.is = is;          this.type = type;          this.os = redirect;      }        public void run() {          try {              PrintWriter pw = null;              if (os != null)                  pw = new PrintWriter(os);              InputStreamReader isr = new InputStreamReader(is);              BufferedReader br = new BufferedReader(isr);              String line = null;              while ((line = br.readLine()) != null) {                  if (pw != null){                pw.println(line);                log.info(line);                }                log.info(type + ">" + line);              }              if (pw != null){            pw.flush();            }                        } catch (IOException e) {              e.printStackTrace();              log.error("错误信息:"+e.getMessage()+" , "+e.getMessage());        }      }      }




参考资料:

1.http://www.javaworld.com/article/2071275/core-java/when-runtime-exec---won-t.html

2.http://www.cnblogs.com/nkxyf/archive/2012/12/13/2815978.html

0 0
原创粉丝点击