3

私は次のコードを持っていますが、なぜそれが機能しないのか理解できません:

final ByteArrayOutputStream bos = new ByteArrayOutputStream();
final String p1 = "HELLO WORLD";
process(p1, bos);
Assert.assertEquals("BOS value should be: "+p1, p1, bos.toString("UTF-8"));

それは印刷します:

junit.framework.ComparisonFailure:BOS値は次のようになります:HELLO WORLD期待:<[HELLO WORLD]>しかし、次のようになりました:<[]> at junit.framework.Assert.assertEquals(Assert.java:81)など...

プロセスは次のようになります。

public static void process(final String p1, final OutputStream os) {
    final Runtime rt = Runtime.getRuntime();
    try {
        final String command = "echo " + p1;
        log.info("Executing Command: " + command);
        final Process proc = rt.exec(command);

        // gobble error and output
        StreamGobbler.go(proc.getErrorStream(), null);
        StreamGobbler.go(proc.getInputStream(), os);

        // wait for the exit
        try {
            final int exitVal = proc.waitFor();
            log.info("Command Exit Code: " + exitVal);
        } catch (InterruptedException e) {
            log.error("Interrupted while waiting for command to execute", e);
        }
    } catch (IOException e) {
        log.error("IO Exception while executing command", e);
    }
}

private static class StreamGobbler extends Thread {
    private final InputStream is;
    private final OutputStream os;

    private static StreamGobbler go(InputStream is, OutputStream os) {
        final StreamGobbler gob = new StreamGobbler(is, os);
        gob.start();
        return gob;
    }

    private StreamGobbler(InputStream is, OutputStream os) {
        this.is = is;
        this.os = os;
    }

    public void run() {
        try {
            final PrintWriter pw = ((os == null) ? null : new PrintWriter(os));
            final InputStreamReader isr = new InputStreamReader(is);
            final BufferedReader br = new BufferedReader(isr);
            String line = null;
            while ((line = br.readLine()) != null) {
                if (pw != null) {
                    pw.println(line);
                }
                log.info(line); // Prints HELLO WORLD to log
            }
            if (pw != null) {
                pw.flush();
            }
        } catch (IOException ioe) {
            log.error("IO error while globbing", ioe);
        }
    }

jUnitテストを実行すると、実際には空の文字列が表示されます。なぜこれがうまくいかないのか分かりません。

編集:それがまったく違いを生むのであれば、私はRHEL5とeclipse3.6を使用しています。

4

1 に答える 1

4

多分あなたはストリームを満たすスレッドを待つべきです:

    Thread thr = StreamGobbler.go(proc.getInputStream(), os);

    // wait for the exit
    try {
        final int exitVal = proc.waitFor();
        log.info("Command Exit Code: " + exitVal);
        thr.join();//waits for the gobbler that processes the stdout of the process
    } catch (InterruptedException e) {
        log.error("Interrupted while waiting for command to execute", e);
    }
于 2011-05-20T23:42:40.640 に答える