Выходной поток байтового массива java ничего не дает

У меня есть следующий код, и я не могу понять, почему он не будет работать:

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]> но было:‹[]> в 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 и eclipse 3.6, если это вообще имеет значение.


person Mohamed Nuur    schedule 20.05.2011    source источник
comment
Укажите вашу операционную систему; ответы могут зависеть от того, является ли эхо приложением или функцией оболочки.   -  person McDowell    schedule 21.05.2011
comment
RHEL5. Я помещаю log.info(строку) в цикл в StreamGlobber, и он печатает HELLO WORLD. Но у моего ByteArrayOutputStream этого нет.   -  person Mohamed Nuur    schedule 21.05.2011
comment
Ваш код выхода из команды и команда выполнения не отображаются в выводе — вы вырезали это?   -  person Bill K    schedule 21.05.2011
comment
Да. Они оба правы. Выполняемая команда: echo HELLO WORLD и код выхода команды: 0   -  person Mohamed Nuur    schedule 21.05.2011


Ответы (1)


возможно, вам следует подождать, пока поток заполнит поток:

    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);
    }
person ratchet freak    schedule 20.05.2011
comment
привести к тому, что основной поток может завершить метод (и пройти через assertEquals) до того, как поток пожирателя сможет запустить и собрать какие-либо данные. - person ratchet freak; 21.05.2011