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

java与shell相互嵌套调用

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

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

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

0818b9ca8b590ca3270a3433284dd417.png

刚开始我的编码如下:

0818b9ca8b590ca3270a3433284dd417.png

可能是因为把

int extValue = process.waitFor();

while ((line = input.readLine()) != null){

log.info("-----  :  "+line);

list.add(line);

}

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

后来看到一个更高级的,

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

代码如下:

0818b9ca8b590ca3270a3433284dd417.png

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值