- PR -

Runtime#exec()と標準出力/エラーについて

1
投稿者投稿内容
POTETO
常連さん
会議室デビュー日: 2003/10/06
投稿数: 41
投稿日時: 2004-05-31 08:41
こんにちは、POTETOです。
JDK1.3の環境です。
少し長くなりますがすいません。
Javaから外部プログラム(OSコマンドなど)を呼び出したい場合に、
Runtime#exec()を使うと思うのですが、ネットで調べたところ
標準出力/エラーのバッファが少ないのでそれぞれ別スレッドで
読み出す必要があるとありました。そこで以下のようなつくりにしたのですが、
(1)Processオブジェクトから取得したInputStreamを読み出しのスレッド側で
クローズして良いものでしょうか。
(2)Processオブジェクトが処理終了時点でInputStreamはクローズされてしまい、
読み出しのスレッドでクローズするときに例外が発生する可能性はあるのでしょうか?
実行すると特にエラーもなく動いているようです。(printlnの出力より判断)

どなたかご教授のほどよろしくお願いいたします。

因みに、以下のコードは実行時の引数をコマンドとして実行するものです。

----- ここからコード-------
コード:
public class Command{
  public static void main(String[] args){
    Runtime runtime = Runtime.getRuntime();
    Process process = null;
    
    try{
      Thread stOut = new ReadConsole("STDOUT");
      Thread stErr = new ReadConsole("STDERR");
      process = runtime.exec(args);
      ((ReadConsole)stdOut).setIs(process.getInputStream);
      ((ReadConsole)stdOut).setIs(process.getErrorStream);
      stOut.start();
      stErr.start();
      process.waitFor();
      int value = process.exitValue();
      System.out.priintln("リターンコード=" + value);
    }catch(Exception e){
    }
  }
}

class ReadConsole extends Thread{
  private InputStream is = null;
  private String type = null;

  public ReadConsole(String type){
    this.type = type;
  }
  public void run(){
    BufferedInputStream bufIs = null;
    byte[] bytes = new byte[50];

    try{
      bufIs = new BufferedInputStream(this.is);
      while(bufIs.read(bytes, 0, 49){
        System.out.println(this.type + " : " + new String(bytes));
      }
    }catch(Exception e){
    }finally{
      try{
        bufIs.close();
        this.is.close();
      }catch(Exception e){
      }
    }
  }

  public void setIs(InputStream is){
    this.is = is;
  }
}

a-san
ベテラン
会議室デビュー日: 2004/06/01
投稿数: 53
投稿日時: 2004-06-01 20:24
私はAntの中のソースを参考にしました。ここら辺です。
org.apache.tools.ant.taskdefs.ExecuteStreamHandler
org.apache.tools.ant.taskdefs.StreamPumper
1

スキルアップ/キャリアアップ(JOB@IT)