---
title: "StreamGobbler方法"
author: "hellsing42"
date: "2007-08-30T10:24:20Z"
tags: []
slug: "streamgobbler"
draft: false
lastmod: "2007-08-30T10:24:20Z"
id: 118305
url: "https://hellsing42.iteye.com/blog/118305"
---

```
class StreamGobbler extends Thread {
  InputStream is;
  String type;
  
  StreamGobbler(InputStream is, String type) {
      this.is = is;
      this.type = type;
  }
  
  public void run() {
      try {
          InputStreamReader isr = new InputStreamReader(is);
          BufferedReader br = new BufferedReader(isr);
          String line=null;
          while ( (line = br.readLine()) != null)
              System.out.println(type + ">" + line);
      } catch (IOException ioe) {
          ioe.printStackTrace();
      }
  }
  // end StreamGobbler
```

调用:

```

			
			Process proc = Runtime.getRuntime().exec(moveCommand);
            //any error message?
            StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR");
            // any output?
            StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT");
            // kick them off
            errorGobbler.start();
            outputGobbler.start();
            // any error???
            int exitVal = proc.waitFor();
            String executeStatus = "";
            if(exitVal==0) executeStatus = "success..";
            if(exitVal==1) executeStatus = "failure....";
            
            System.out.print(executeStatus);
            

```

具体原来不知道是如何,但是效果是可以有效的监控Runtime.getRuntime.exec("")是否有效的执行完成,当执行完成后才继续执行下面的程序.希望有其中的原理