How can I make a copy of a BufferedReader?

后端 未结 3 2132
醉话见心
醉话见心 2020-12-03 11:27

I am using a BufferedReader constructor to make a new copy of an existing BufferedReader.

BufferedReader buffReader = new BufferedR         


        
3条回答
  •  渐次进展
    2020-12-03 12:27

    Below is one way to consider creating a new BufferedReader out of the Original BufferedReader.

    Essentially, we are dumping the contents of the original buffered reader into a string and then recreating a new BufferedReader object. To be able to re read the original BufferedReader a second time you can mark it and then after reading it, you can then reset it.

    One thing to keep in mind is you might want to protect by DDOS attacks, where a very large buffered reader can come in and you might want to avoid reading for ever and filling up the memory, you can basically break the for loop after some point or when a certain condition is met.

    final String originalBufferedReaderDump;
    originalBufferedReaderDump.mark(Integer.MAX_VALUE);
    for (String line; (line = originalBufferedReader.readLine()) != null; originalBufferedReaderDump+= line);
    originalBufferedReader.reset();
    final BufferedReader copiedBufferedReader  = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(originalBufferedReaderDump.getBytes())));
    

提交回复
热议问题