29

私はここで頭がいっぱいです。これは単純なことだと確信しており、Java とストリームの理解に大きな穴がある可能性が高いです。非常に多くのクラスがあるため、API を調べて、多数の入出力ストリームをいつどのように使用するかを把握するのに少し圧倒されていると思います。

apache commons ライブラリの存在を知ったばかりで (Java の自己学習は失敗します)、現在、Runtime.getRuntime().exec の一部を変換して commons を使用しようとしています - exec. 6 か月に 1 回発生するこの問題の一部はすでに修正されており、exec のスタイルの問題は解消されています。

このコードは perl スクリプトを実行し、スクリプトの実行中にスクリプトからの stdout を GUI に表示します。

呼び出しコードは、swingworker の内部にあります。

pumpStreamHandler の使用方法がわかりません... とにかく古いコードは次のとおりです。

String pl_cmd = "perl script.pl"
Process p_pl = Runtime.getRuntime().exec( pl_cmd );

BufferedReader br_pl = new BufferedReader( new InputStreamReader( p_pl.getInputStream() ) );

stdout = br_pl.readLine();
while ( stdout != null )
{
    output.displayln( stdout );
    stdout = br_pl.readLine();
}

これは、ずっと前に完全には理解できなかったコピーペーストコードに対して得られるものだと思います。上記はプロセスを実行していると仮定し、出力ストリームを取得して(「getInputStream」を介して)、バッファリングされたリーダーに配置し、バッファが空になるまでそこでループします。

私が得られないのは、ここで「waitfor」スタイルのコマンドが必要ない理由です? バッファが空になり、ループを終了し、プロセスがまだ進行している間に続行する時間がある可能性はありませんか? 実行すると、そうではないようです。

いずれにせよ、私は commons exec を使用して同じ動作を得ようとしています。

DefaultExecuteResultHandler rh = new DefaultExecuteResultHandler();
ExecuteWatchdog wd  = new ExecuteWatchdog( ExecuteWatchdog.INFINITE_TIMEOUT );
Executor exec = new DefaultExecutor();

ByteArrayOutputStream out = new ByteArrayOutputStream();
PumpStreamHandler psh = new PumpStreamHandler( out );

exec.setStreamHandler( psh );
exec.setWatchdog( wd );

exec.execute(cmd, rh );
rh.waitFor();

pumpstreamhandler が何をしているかを把握しようとしています。これは exec オブジェクトからの出力を取得し、OutputStream に perl スクリプトの stdout/err からのバイトを入力します。

もしそうなら、どのように上記の動作を取得して、出力を行ごとにストリーミングしますか? 例では、最後に out.toString() を呼び出すことを示していますが、スクリプトの実行が完了すると、スクリプトからのすべての出力のダンプが得られると思いますか? 行ごとに実行されているときに出力が表示されるようにするにはどうすればよいですか?

------------ 今後の編集 ----------------------

Google経由でこれを見つけて、同様にうまく機能します:

public static void main(String a[]) throws Exception
{
    ByteArrayOutputStream stdout = new ByteArrayOutputStream();
    PumpStreamHandler psh = new PumpStreamHandler(stdout);
    CommandLine cl = CommandLine.parse("ls -al");
    DefaultExecutor exec = new DefaultExecutor();
    exec.setStreamHandler(psh);
    exec.execute(cl);
    System.out.println(stdout.toString());
}
4

4 に答える 4

31

にを渡さないでください。抽象クラスの実装を使用ByteArrayOutputStreamしてください。javadocから:PumpStreamHandlerorg.apache.commons.exec.LogOutputStream

実装は、着信データを解析して行を作成し、行全体をユーザー定義の実装に渡します。

したがって、LogOutputStramは出力を前処理して、生のバイトではなく個々の行を処理する制御を提供します。このようなもの:

import java.util.LinkedList;
import java.util.List;
import org.apache.commons.exec.LogOutputStream;

public class CollectingLogOutputStream extends LogOutputStream {
    private final List<String> lines = new LinkedList<String>();
    @Override protected void processLine(String line, int level) {
        lines.add(line);
    }   
    public List<String> getLines() {
        return lines;
    }
}

次に、あなたへのブロック呼び出しの後、exec.executeあなたgetLines()が探している標準出力と標準エラーが発生します。これExecutionResultHandlerは、プロセスを実行し、すべてのstdOut/stdErrを行のリストに収集するという観点からはオプションです。

于 2012-09-06T13:30:34.317 に答える
3

ここで「waitfor」スタイルのコマンドが必要ないのはなぜですか?バッファが空になり、ループを終了して、プロセスがまだ進行している間に続行する時間がある可能性はありませんか?私がそれを実行するとき、これはそうではないようです。

readLineブロック。つまり、コードは行が読み取られるまで待機します。

PumpStreamHandler

ドキュメントから

サブプロセスの標準出力とエラーを親プロセスの標準出力とエラーにコピーします。出力またはエラーストリームがnullに設定されている場合、そのストリームからのフィードバックはすべて失われます。

于 2011-09-07T21:09:51.213 に答える
3

James A Wilson の回答に基づいて、ヘルパー クラス「Execute」を作成しました。彼の答えを、便宜上 exitValue も提供するソリューションにラップします。

この方法でコマンドを実行するには、1 行が必要です。

ExecResult result=Execute.execCmd(cmd,expectedExitCode);

次の Junit テストケースは、テストを行い、その使用方法を示しています。

Junit4 テスト ケース:

package com.bitplan.newsletter;

import static org.junit.Assert.*;

import java.util.List;

import org.junit.Test;

import com.bitplan.cmd.Execute;
import com.bitplan.cmd.Execute.ExecResult;

/**
 * test case for the execute class
 * @author wf
 *
 */
public class TestExecute {
     @Test
   public void testExecute() throws Exception {
     String cmd="/bin/ls";
     ExecResult result = Execute.execCmd(cmd,0);
     assertEquals(0,result.getExitCode());
     List<String> lines = result.getLines();
     assertTrue(lines.size()>0);
     for (String line:lines) {
         System.out.println(line);
     }
   }
}

Java ヘルパー クラスを実行します。

package com.bitplan.cmd;

import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;

import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.LogOutputStream;
import org.apache.commons.exec.PumpStreamHandler;

/**
 * Execute helper using apache commons exed
 *
 *  add this dependency to your pom.xml:
   <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-exec</artifactId>
            <version>1.2</version>
        </dependency>

 * @author wf
 *
 */
public class Execute {

    protected static java.util.logging.Logger LOGGER = java.util.logging.Logger
            .getLogger("com.bitplan.cmd");

    protected final static boolean debug=true;

    /**
     * LogOutputStream
     * http://stackoverflow.com/questions/7340452/process-output-from
     * -apache-commons-exec
     * 
     * @author wf
     * 
     */
    public static class ExecResult extends LogOutputStream {
        private int exitCode;
        /**
         * @return the exitCode
         */
        public int getExitCode() {
            return exitCode;
        }

        /**
         * @param exitCode the exitCode to set
         */
        public void setExitCode(int exitCode) {
            this.exitCode = exitCode;
        }

        private final List<String> lines = new LinkedList<String>();

        @Override
        protected void processLine(String line, int level) {
            lines.add(line);
        }

        public List<String> getLines() {
            return lines;
        }
    }

    /**
     * execute the given command
     * @param cmd - the command 
     * @param exitValue - the expected exit Value
     * @return the output as lines and exit Code
     * @throws Exception
     */
    public static ExecResult execCmd(String cmd, int exitValue) throws Exception {
        if (debug)
            LOGGER.log(Level.INFO,"running "+cmd);
        CommandLine commandLine = CommandLine.parse(cmd);
        DefaultExecutor executor = new DefaultExecutor();
        executor.setExitValue(exitValue);
        ExecResult result =new ExecResult();
        executor.setStreamHandler(new PumpStreamHandler(result));
        result.setExitCode(executor.execute(commandLine));
        return result;
    }

}
于 2014-07-31T10:22:24.570 に答える