0

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 BufferedReader (second one) in this case? Does it is correct?

4
  • 2
    Have you tried it? The answer is that it works and wastes time and space. Commented Oct 5, 2011 at 12:07
  • 1
    "Have you tried it" is not a great response. Trying it can only tell you that something works (or doesn't) in one specific setting. It doesn't tell you if it's always going to work or if it's bad design or if it works, but only by chance ... Commented Oct 5, 2011 at 12:08
  • I haven't try it. I want use same statement in my project. But I think it would be very slow. Commented Oct 5, 2011 at 12:09
  • It almost certainly wouldn't be "very slow". There might be a very small performance penalty, but the actual file I/O is almost definitely several magnitudes bigger than that overhead (even with the fastest SSDs available). Commented Oct 5, 2011 at 12:15

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot! Actually, I'll review design of my project.
1

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.