java字节数组输出流什么都没有

时间:2011-05-20 23:23:15

标签: java exec bytearrayoutputstream

我有以下代码,我无法弄清楚为什么它不起作用:

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,如果它有所作为。

1 个答案:

答案 0 :(得分: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);
    }