输入输出流的重定向

前不久做项目的时候碰到了需要测试用户输入的问题,就是向别人证明用户在控制台输入什么,你就能准确地输出什么。怎么通过测试来模拟这种情况,着实折腾了很久,最后参考别人的做法----输入输出流重定向。

    private PipedOutputStream redirectedInput;

    private OutputStreamWriter redirectedInputWriter;

    private ByteArrayOutputStream redirectedOutput;

    private ByteArrayOutputStream redirectedError;

    private InputStream standardInputStream;

    private PrintStream standardOutputStream;

    private PrintStream standardErrorStream;

 

    /**

     * <p>

     * Sets up the test environment.

     * </p>

     *

     * @throws IOException

     *             to JUnit

     */

    @Override

    protected void setUp() throws IOException {

        // redirects the current standard input / output / error stream

        standardInputStream = System.in;//本来这个输入流是连接键盘

        standardOutputStream = System.out;//本来这个输出流是连接屏幕的

        standardErrorStream = System.err;//这个输出流也是连接屏幕的

 

        // creates the input / output / error stream for testing

        redirectedInput = new PipedOutputStream();

        redirectedInputWriter = new OutputStreamWriter(redirectedInput);

        System.setIn(new PipedInputStream(redirectedInput));

        //现在输入流连接redirectedInputWriter

        //一有东西写入到redirectedInputWriter,就会跑向他的目的地redirectedInput

        //然后再通过管道流pipeInputStream跑到system.in里去,于是模拟了

        //用户输入----程序通过system.in获得用户输入

 

        redirectedOutput = new ByteArrayOutputStream();

        System.setOut(new PrintStream(redirectedOutput));

        //现在输出流连接redirectedOutput

        //一有东西写入到system.out就会跑向他得目的地redirectedOutput

        //以前我们从屏幕读输出信息,现在我们可以从redirectedOutput读信息来验证程序的输出

       

        redirectedError = new ByteArrayOutputStream();

        System.setErr(new PrintStream(redirectedError));

    }

 

    /**

     * <p>

     * Tears down the test environment.

     * </p>

     *

     * @throws IOException

     *             to JUnit

     */

    @Override

    protected void tearDown() throws IOException {

        // closes the input / output / error stream for testing

        redirectedInputWriter.close();

        redirectedInput.close();

        System.in.close();

 

        redirectedOutput.close();

        System.out.close();

 

        redirectedError.close();

        System.err.close();

 

        // redirects the previous standard input / output / error stream

        System.setIn(standardInputStream);

        System.setOut(standardOutputStream);

        System.setErr(standardErrorStream);

 

    }

posted @ 2010-07-10 15:27  明之道  阅读(1197)  评论(0编辑  收藏  举报