如何从ByeArrayOutputStream恢复BufferedReader对象

时间:2017-07-05 14:54:13

标签: java deserialization bufferedreader bytearrayinputstream

我编写了一个代码来存根System.out.println并将BuffredReader的对象传递给它。 我的问题是如何恢复BufferedReader对象?

import java.io.*;

class Test {

  public static void main(String args[]) throws IOException {
    // stubbing the default print statement
    ByteArrayOutputStream outcontent = new ByteArrayOutputStream();
    System.setOut(new PrintStream(outcontent);

      //createing a BufferedReader obj and passing to print
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 
      System.out.println(br);

      //trying to get the value from the outcontent and 
      // but i need to serialise this to BufferedReader
      System.err.println(outContent.toString());

    }
  }

我尝试使用this answer,但收到错误java.io.StreamCorruptedException: invalid stream header: 6A617661

1 个答案:

答案 0 :(得分:0)

由于你已经有ByteArrayOutputStream,你应该尝试这样的事情:

BufferedReader reader = new BuffererdBeader( new InputStreamReader(
                            new ByteArrayInputStream( outcontent.toByteArray() ) ) );