开发者

Construct BufferedReader with BufferedReader as reader

Can I do this subj? I mean:

 BufferedReader reader1 = new BufferedReader(new FileReader(new File("file")));
 BufferedReader reader2 = new BufferedReader(reader1);

What will happen if I'll try to use BufferedRead开发者_开发百科er (second one) in this case? Does it is correct?


It is correct in the sense that it will work:

You can construct a BufferedReader from any valid Reader, even another BufferedReader.

It won't really improve performance or have any other beneficial effects, however. You should simply use reader1 and not create the second one.

It can even have negative effects if you start mixing calls to reader1 and reader2, but that's just the general idea of stream in Java: once you wrap a stream (or reader/writer), you should no longer access it directly.


Yes, you can decorate any Reader with a BufferedReader, but it doesn't give you any benefit.


It will use the below constructor to create the second BufferedReader. I would assume there would be a subtle performance loss because now you have two buffers with the same size.

 /**
  * Creates a buffering character-input stream that uses a default-sized
  * input buffer.
  *
  * @param  in   A Reader
  */
  public BufferedReader(Reader in) {
      this (in, defaultCharBufferSize);
  }

http://developer.classpath.org/doc/java/io/BufferedReader-source.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜